typescript - 使用 Pick 为具有索引类型的对象构造类型
问题描述
给定以下界面:
interface Foobar {
things?: { [key: string]: string[] };
}
PickType可以用来创建类型以供重用吗?
// Manually typing it works:
// type Part { [key: string]: string[] }
// this does not:
type Part = Pick<Foobar, "things">;
const something: Part = { x: ["a", "b"] } };
Object.keys(something).forEach((thing) => {
const needThis = something[thing];
console.log(needThis); // <- this should return ["a", "b"]
});
使用此处的示例创建了一个代码框:https ://codesandbox.io/s/tender-edison-ejck8?file=/src/index.ts
代码编译,但有警告:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Pick<Foobar, "things">'.
No index signature with a parameter of type 'string' was found on type 'Pick<Foobar, "things">'
解决方案
Pick
将使用作为第二个参数提供的键创建一个子类型。因此,在您的示例中,您将拥有这样的类型:
type Something {
someThing: { [key: string]: string[] };
}
编辑:正如评论中提到的@mbdavis 在Pick
这里似乎完全多余:
如果要使用属性类型,还应提供属性名称,如下所示:
type SomeInterface = Foobar["someThing"]
推荐阅读
- android - FCM 令牌是特定于应用程序还是设备?
- r - 如何使数组中的最大值小于另一个数组的每个值(R)
- angular - 从字符串数组中获取 keyof 类
- php - PHP - 在特定日期阅读限制的电子邮件
- python - 从字符串中剪切特定部分,删除 HTML 标签。[网页抓取]
- spring-cloud-stream-binder-kafka - Kakfa 消息在数据库事务之前提交
- gcc - 在代码中使用 ThreadSanitizer 的 Mutex 名称
- sql-server - 适用于 SQL Server 2019 开发人员的 Oracle 提供程序链接
- php - CKEditor 5 自定义图像上传确实上传了文件,但编辑器说它不是
- json - 如何从 json.loads() 字典中获取值?