所以,我有:
interface Foo {
type: FooType;
}
Run Code Online (Sandbox Code Playgroud)
哪一个更适合在FooType这里使用:
输入别名?
type FooType = 'BAR' | 'BAZ';
Run Code Online (Sandbox Code Playgroud)
还是基于字符串的枚举?
enum FooType {
BAR = 'BAR',
BAZ = 'BAZ'
}
Run Code Online (Sandbox Code Playgroud)
两者的优缺点是什么?
您的第一个示例(您将其称为“类型别名”)实际上称为字符串文字类型。
我认为这取决于个人喜好。
枚举
const enum它来避免这种情况)字符串字面量
string类型化值时,通常必须any在断言值之前先断言let x: string
let y: FooType
y = x as any as FooType
Run Code Online (Sandbox Code Playgroud)
(编辑:嗯,看起来他们解决了这个问题)
我曾经更喜欢枚举,但最近我更倾向于字符串文字类型。再说一遍,我认为这一切都取决于个人喜好。
| 归档时间: |
|
| 查看次数: |
1142 次 |
| 最近记录: |