简体   繁体   English

如何在 TypeScript 中获取接口属性的类型?

[英]How to get the type of an interface property in TypeScript?

So I have a code like:所以我有一个类似的代码:

interface MyInterface{
  a:any,
  b:string,
  c:boolean,
  d:number,
  readonly valueChanges:Subject<{key: keyof MyInterface, value: ???}>
}

where I dont know how to write the type of the value under the correct 'key'.我不知道如何在正确的“键”下写入值的类型。 I have tried the typeof MyInterface[key] but probably this is not how to solve it.我已经尝试了typeof MyInterface[key]但这可能不是解决它的方法。 :( :(

Thanks for your time in advance!提前感谢您的时间!

You can make use of the AllValues utility type posted by Titian Cernicova-Dragomir .您可以使用由Titian Cernicova-Dragomir发布的AllValues实用程序类型。 Note that you do not need the extends Record<PropertyKey, PropertyKey> as that is specific to the problem of inverting.请注意,您不需要extends Record<PropertyKey, PropertyKey>因为它特定于反转问题。

type AllValues<T> = {
    [P in keyof T]: { key: P, value: T[P] }
}[keyof T]

You then apply this type to your interface, but make sure that {key: valueChanges...} isn't one of your options.然后将此类型应用于您的界面,但请确保{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">>>;
}

I don't like the circular referencing here, so personally I would break it into composable pieces.我不喜欢这里的循环引用,所以我个人会将它分解成可组合的部分。 MyInterface would end up as a type rather than an interface , but there is very little practical difference. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM