如何从 TypeScript 中的枚举值构建类型? [英] How to build a type from enum values in TypeScript?

查看:35
本文介绍了如何从 TypeScript 中的枚举值构建类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下内容:

enum FooKeys {
  FOO = 'foo',
  BAR = 'bar',
}

我想制作一个这样的界面,但不是手动定义键,而是使用枚举的值构建它.

I'd like to make an interface like this one, but instead of defining keys by hand, build it out of enum's values.

interface Foo {
  foo: string
  bar: string
}

TypeScript 可以实现类似的功能吗?

Is something like this possible with TypeScript?

谢谢!

推荐答案

是的,您可以使用枚举值作为键.您可以使用映射类型,就像标准库的记录 防止重复:

Yes, you can use enum values as keys. And you can use a mapped type like the standard library's Record<K, V> to prevent repetition:

enum FooKeys {
  FOO = 'foo',
  BAR = 'bar',
}

// probably all you need, but it's a type alias
type FooType = Record<FooKeys, string>;

// if you need an interface instead you can do this
interface FooInterface extends FooType {};

您可以验证它是否有效:

And you can verify that it works:

declare const foo: FooInterface;
foo.foo; // okay
foo[FooKeys.FOO]; // okay

foo.bar; // okay
foo[FooKeys.BAR]; // okay

foo.baz; // error

这对你有用吗?祝你好运!

Does that work for you? Good luck!

这篇关于如何从 TypeScript 中的枚举值构建类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆