【问题标题】:How to get the type of an interface property in TypeScript?如何在 TypeScript 中获取接口属性的类型?
【发布时间】:2021-01-18 10:11:15
【问题描述】:

所以我有这样的代码:

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

我不知道如何在正确的“键”下写入值的类型。我已经尝试过typeof MyInterface[key],但可能这不是解决方法。 :(

提前感谢您的宝贵时间!

【问题讨论】:

  • Subject的签名是什么?是函数吗?
  • @PritamKadam 我不确定它为什么重要。它只是一个通用的 - 可能是一个类或不是一个类。我看不出它会如何改变任何答案。
  • 可以这样定义,并且可以正确推断类型:readonly valueChanges: &lt;K extends keyof MyInterface&gt;(k: K, v: MyInterface[K]) =&gt; void

标签: typescript


【解决方案1】:

您可以使用Titian Cernicova-Dragomir 发布的AllValues 实用程序类型。请注意,您不需要extends Record&lt;PropertyKey, PropertyKey&gt;,因为这是特定于反转问题的。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 2020-02-28
    • 2023-03-10
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多