【问题标题】:Create literal without repeating in typescript创建文字而不在打字稿中重复
【发布时间】:2017-11-01 09:20:57
【问题描述】:

如何在不重复值的情况下创建具有文字类型的只读对象。

'myLiteralValue' 显式键入的工作示例:

const createSettings = () => ({ appType: 'myLiteralValue' as 'myLiteralValue' });

switch (createSettings().appType) {
  case 'myLiteralValue':
    break;
}

如果我没有明确键入,类型会扩大到 string,如果我删除重复的 'myLiteralValue',则会进行切换

const createSettings = () => ({ appType: 'myLiteralValue' });

switch (createSettings().appType) {
  case 'myLiteralValue':
    break;
}

虽然将 appType 分解为 const 仍会重复,但方式不同:

const myLiteralValue = 'myLiteralValue';
const createSettings = () => ({ appType: myLiteralValue });

switch (createSettings().appType) {
  case 'myLiteralValue':
    break;
}

【问题讨论】:

  • 破解如何?什么意思?
  • this part of the documentation 有帮助吗?我不确定您所说的“重复”是什么意思。您始终可以使用 const 而不是使用 typeof 来获取文字类型。
  • @NitzanTomer 我用澄清更新了示例
  • @SebastianSebald 有点像,但我仍然需要为该类型创建一个接口,这将使我在接口中重复字符串“myLiteralValue”
  • 你的真实代码是什么样的?显然,appType 可以有更多值,因此文字也有多个值,而不是像您的示例中那样只有一个。此外,即使appType 是字符串,您的代码在操场上也很好,那么到底是什么问题?

标签: typescript


【解决方案1】:

您可以使用readonly 修饰符来声明常量属性(在本例中为文字属性)。

class Settings {
    constructor(public id: any) { }
    readonly appType: "myLiteralValue";
}

const createSettings = (id: any) => new Settings(id);

【讨论】:

    猜你喜欢
    • 2020-05-03
    • 2019-06-02
    • 2021-12-12
    • 1970-01-01
    • 2018-10-27
    • 2019-11-25
    • 2019-11-28
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多