typescript - 如何在 typescript 中使用字符串类型的联合

标签 typescript

我想在 typescript 中创建自定义类型,如下所示:

color?: 'textPrimary' | 'textSecondary' | string;

所以我们有一些默认值和其他字符串。

但 typescript 将其转换为 string | undefined

我怎样才能实现这个目标?

最佳答案

正如 Ben 所评论的那样,无需为您想要回退的额外值定义类型,因为它们也是 string 类型。

无论如何,您可能有兴趣使用 enums这样您就可以存储您尝试保存的那些“默认值”。这对代码的 future 很有帮助,因此如果需要将这些值更改为另一个默认字符串,您只能更改 enum 而不是转到每个硬编码字符串并逐一更改它们.

做这样的事情:


enum defaultClasses {
    primary = 'textPrimary',
    secondary = 'textSecondary'
}

class baseProp {
    color?: defaultClasses | string
}

const prop = new baseProp()
prop.color = defaultClasses.primary
console.log(prop.color) # 'textPrimary'

关于typescript - 如何在 typescript 中使用字符串类型的联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68807772/

相关文章:

typescript - 在条件类型上通过泛型传递联合会分配 any 而不是联合

javascript - Angular 处理多个依赖订阅

javascript - 对 3 个嵌套数组感到困惑

typescript - 如何指定 TypeScript 匿名内联箭头函数的返回类型

typescript - 尝试将节点模块导入 NuxtJS TypeScript 时出错(ES2018)

javascript - Angular 2 中的 Leaflet + Google - 瓷砖顺序错误

javascript - 无法从单选按钮 ionic 3 获取值

typescript - 有没有办法在 typescript 中显示类型的规范化版本?

typescript - TS 中字符串枚举和字符串文字类型之间的区别

angular - 为 typescript 中的 Observable 导入 .of()