typescript - 如何确保 T['someDynamicField'] 是 K 类型
问题描述
interface Props<KeyType, T> {
keyField : keyof T; //what field to use as key. Key of type KeyType
data: T[]; //Data provided to table
}
如何确保它T[keyField]
是 KeyType 类型?
我想要达到的目标:
//selection is of type KeyType[]
//props implements interface Props
selection.filter(key => !props.data.filter(item => key === item[props.keyField]).length).forEach(
key => { /*...*/})
有效。现在,如果我使用 KeyType == string 实现 Props,它会给我一个错误:
TS2367: This condition will always return 'false' since the types 'string' and 'T[keyof T]' have no overlap.
解决方案
以下是我用来完成此操作的一些实用程序类型:
//gets the set of keys on Obj which are assignable to Type
export type FilteredProperties<Obj, Type> = { [key in keyof Obj]: Obj[key] extends Type ? key : never }[keyof Obj];
//gets the set of keys on Obj which can be assigned from Type
export type FilteredPropertiesAssign<Obj, Type> = { [key in keyof Obj]: Type extends Obj[key] ? key : never }[keyof Obj];
要使用:
interface example {
field1: string;
field2: number;
}
interface Props<T, TargetType, KeyType extends FilteredProperties<T, TargetType>> {
keyField: KeyType;
data: T[];
}
type test1 = Props<example, string, "field1">; //ok
type test2 = Props<example, number, "field2">; //ok
type test3 = Props<example, string, "field2">; //error
推荐阅读
- android - 仅在 XML 中在 imageview 上绘制 android:foreground
- php - 如果结果 = 0,我如何禁用表格行
- mysql - Mysql 错误 1111:在更新中使用组函数无效
- html - 在另一个页面上链接和使用特定的 html 标记
- presto - 我在 Athena 上的嵌套选择语句出现问题(无法解析列)
- wordpress - woocommerce 产品 - 缺少产品 ID、缺少品牌名称和缺少谷歌搜索控制台的可用性
- docker - docker run 和 docker pull 有什么区别
- python-3.x - 为什么我在运行我的程序时不断收到 AttributeError: 'str' object has no attribute 'Student'
- javascript - 如何在 Windows 上使用单个 NPM 命令运行多个 NPM 命令
- python - 少单与守序相结合