【发布时间】:2019-06-15 05:15:32
【问题描述】:
我有以下几点:
type CommandTypes = 'one' | 'two' | 'three';
const CONST = {
commands: {
a: 'one',
b: 'two',
c: 'error'
},
};
有没有办法强制所有命令都属于特定类型?
现在 TypeScript 告诉我 a、b 和 c 属于 string 类型,但是我想强制这些属性为 CommandTypes 类型,以便开发人员无法指定任意字符串。我希望 TypeScript 能够捕获 c 无效的错误,因为它不属于允许的 CommandTypes。
如果我以这种方式分解 CONST 定义:
type CommandTypes = 'one' | 'two' | 'three';
const commands : CommandTypes = {
a: 'one',
b: 'two',
c: 'error'
}
const CONST = {
commands,
};
然后这实际上用 c 捕获了错误,但是现在我在 Visual Studio 代码中也失去了自动完成功能。如果我输入 CONST.commands。 我现在不会在此处获得任何自动完成功能,就像我将定义保留在帖子顶部一样,那么我确实会获得自动完成功能。
【问题讨论】:
-
Record
会给你一个对象,它的键是 CommandTypes,它们的值是字符串
标签: typescript interface type-safety