[英]How to get the type of an interface property in TypeScript?
所以我有一个类似的代码:
interface MyInterface{
a:any,
b:string,
c:boolean,
d:number,
readonly valueChanges:Subject<{key: keyof MyInterface, value: ???}>
}
我不知道如何在正确的“键”下写入值的类型。 我已经尝试了typeof MyInterface[key]
但这可能不是解决它的方法。 :(
提前感谢您的时间!
您可以使用由Titian Cernicova-Dragomir发布的AllValues
实用程序类型。 请注意,您不需要extends Record<PropertyKey, PropertyKey>
因为它特定于反转问题。
type AllValues<T> = {
[P in keyof T]: { key: P, value: T[P] }
}[keyof T]
然后将此类型应用于您的界面,但请确保{key: valueChanges...}
不是您的选项之一。
type KeyValueObject = AllValues<Omit<MyInterface, "valueChanges">>
interface MyInterface{
a: any;
b: string;
c: boolean;
d: number;
readonly valueChanges: Subject<AllValues<Omit<MyInterface, "valueChanges">>>;
}
我不喜欢这里的循环引用,所以我个人会将它分解成可组合的部分。 MyInterface
最终会成为一个type
而不是一个interface
,但实际上几乎没有区别。
interface BaseInterface {
a: any;
b: string;
c: boolean;
d: number;
}
type WithValueChanges<T> = T & {
readonly valueChanges: Subject<AllValues<T>>
}
type MyInterface = WithValueChanges<BaseInterface>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.