简体   繁体   English

打字稿,将接口键转换为可能的字符串值的枚举

[英]Typescript, transform interface keys into enum of possible string values

Let's pretend that I have an interface like so:让我们假设我有一个这样的界面:

export interface MyInterface {
  keyA: string;
  keyB: number;
  keyC: boolean;
}

From this interface, I would like to dynamically create a union type that has 'keyA', 'keyB' and 'keyC' as possible values.从这个界面,我想动态创建一个联合类型,它有 'keyA'、'keyB' 和 'keyC' 作为可能的值。

If I had to manually create it, it would result in something like:如果我必须手动创建它,它会导致类似:

export type MyType = 'keyA' | 'keyB' |'keyC';

Is that possible to achieve with Typescript?这可以用 Typescript 实现吗?

尝试这个:

export type MyType = keyof MyInterface;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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