我想在 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/