[英]How to define string literal union type from constants in Typescript
我知道我可以定义字符串联合类型以将变量限制为可能的字符串值之一:
type MyType = 'first' | 'second'
let myVar:MyType = 'first'
我需要从常量字符串构造一个类似的类型,例如:
const MY_CONSTANT = 'MY_CONSTANT'
const SOMETHING_ELSE = 'SOMETHING_ELSE'
type MyType = MY_CONSTANT | SOMETHING_ELSE
但由于某种原因,它不起作用; 它说MY_CONSTANT refers to a value, but it being used as a type here
。
为什么 Typescript 允许第一个例子,但不允许第二个例子? 我在打字稿 3.4.5
要获取变量的类型,您需要使用typeof
类型运算符:
const MY_CONSTANT = 'MY_CONSTANT' // must be const, no annotation. let or var will not work
const SOMETHING_ELSE = 'SOMETHING_ELSE' // must be const, no annotation. let or var will not work
type MyType = typeof MY_CONSTANT | typeof SOMETHING_ELSE
笔记:
因为人们使用它时似乎有很多困惑。 const
很重要。 如果您使用其他类型的声明( let
或var
),最终类型将是字符串。 只有const
保留字符串文字类型。
笔记2:
要使此解决方案起作用,您不得在const
上指定任何类型注释,并让编译器推断常量的类型(例如,这将不起作用: const MY_CONSTANT: string = 'MY_CONSTANT'
)
在这种情况下,您也可以使用枚举。 例如:
// Define enum.
enum myConstants {
MY_CONSTANT = 'my_constant',
SMTH_ELSE = 'smth_else'
}
// Use it in an interface for typechecking.
interface MyInterface {
myProp: myConstants
}
// Example of correct object - no errors.
let a: MyInterface = {
myProp: myConstants.MY_CONSTANT
}
// Incorrect value - TS reports an error.
let b: MyInterface = {
myProp: 'John Doe'
}
枚举很好地涵盖了这个案例:
export enum ITEM_TYPES {
TYPE1 = 'text',
TYPE2 = 'image'
}
export type IItemType = ITEM_TYPES.TYPE1 | ITEM_TYPES.TYPE2
然后在代码中可以引用 ITEM_TYPES 进行所有类型的运行时比较:
if (type === ITEM_TYPES.TYPE1){
}
我发表了与字符串文字联合类型相关的帖子。 https://medium.com/@m.fatihalaziz/string-literal-union-type-with-typeguard-in-typescript-dff4c9741b4a
它涵盖的内容:
我希望它有帮助,祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.