首页 > 解决方案 > 如何确保 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.

标签: typescript

解决方案


以下是我用来完成此操作的一些实用程序类型:

//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

推荐阅读