【问题标题】:Typescript: How to add type safety to object properties?打字稿:如何为对象属性添加类型安全?
【发布时间】:2019-06-15 05:15:32
【问题描述】:

我有以下几点:

type CommandTypes = 'one' | 'two' | 'three';
const CONST = {
  commands: {
    a: 'one',
    b: 'two',
    c: 'error'
  },
};

有没有办法强制所有命令都属于特定类型?

现在 TypeScript 告诉我 abc 属于 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


【解决方案1】:

Record<CommandTypes, string> 会给你一个对象,它的键是 CommandType 的分布式联合,值必须是字符串。注意:如果你想为每个键使用不同的类型,你只能在右侧有一个类型,你必须阅读关于映射类型的 typescripts 文档

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2018-09-17
    • 2021-12-06
    • 2020-04-28
    • 2021-06-19
    • 2019-06-13
    • 2017-09-06
    • 2018-08-03
    相关资源
    最近更新 更多