如何确保T ['someDynamicField']的类型为K

时间:2019-02-01 15:35:11

标签: typescript

  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.

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找类似的东西?

interface Props<T, K extends keyof T> {
  keyField: K
  data: T[K]
}

它称为lookup type。如果不是您想要的东西,请扩展您的问题,以便于理解。

答案 1 :(得分:0)

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

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