[英]Typescript: get type of interface property based on interface key
I'm building a function that needs to update one field of an object at a time.我正在构建一个 function 需要一次更新 object 的一个字段。 this object is defined through an interface
T
.这个 object 是通过接口
T
定义的。
interface T {
a: TypeA;
b: TypeB;
c: TypeC;
}
This should be the type signature of this function:这应该是这个 function 的类型签名:
(key: keyof T, value: typeof T[key]) => void
This generates the error: 'key' refers to a value, but it is being used as a type here. Did you mean 'typeof key'?
这会产生错误:
'key' refers to a value, but it is being used as a type here. Did you mean 'typeof key'?
'key' refers to a value, but it is being used as a type here. Did you mean 'typeof key'?
. . IMO I did not mean
typeof key
, since typeof key
would be any key of T
, but I want the value
attribute to be of type TypeA
if key = a
, etc. IMO我不是说
typeof key
,因为typeof key
可以是T
的任何键,但是如果key = a
等,我希望value
属性为TypeA
类型。
How can I select the type of the corresponding key value of T
?我怎样才能 select
T
的对应键值的类型?
You are trying to index a type with a real value, and this is not allowed.您正在尝试使用实际值索引类型,这是不允许的。 You need to access it with a type ( playground ):
您需要使用类型( playground )访问它:
interface T {
a: number;
b: string;
c: boolean;
}
const func = <K extends keyof T>(key: K, value: T[K]) => {};
func("a", 5);
func("b", 5); // Argument of type 'number' is not assignable to parameter of type 'string'.
There is a clear distinction between types and real values in typescript since the type information is lost after transpilation. typescript 中的类型和实际值之间有明显的区别,因为类型信息在转译后丢失。 Thus you cannot use real values to define type logic.
因此,您不能使用实际值来定义类型逻辑。 The only way would be to extract the type value of a real value (eg, with
typeof
), which is why the compiler suggests transitioning your real value into a type.唯一的方法是提取真实值的类型值(例如,使用
typeof
),这就是编译器建议将真实值转换为类型的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.