[英]Use const values as union type options Typescript
考虑这个例子:
const FIRST = "FIRST"
const SECOND = "SECOND"
type TOptions = FIRST | SECOND
const someFunction = (options: TOptions): void => {
// do something, no return
}
我喜欢在类型声明中使用 const 值
type TOptions = FIRST | SECOND // not working
限制选择范围。 这些 const 在整个项目中使用,因此不使用它们并像这样键入它是不明智的:
type TOptions = "FIRST" | "SECOND" // working, as expected
我不想重复自己并且喜欢使用const
值作为类型联合选项。
我怎么做?
我相信您需要使用typeof
才能使其工作:
const FIRST = 'FIRST'
const SECOND = 'SECOND'
type TOptions = typeof FIRST | typeof SECOND;
const someFunction = (options: TOptions): void => {
// do something, no return
}
someFunction(FIRST); // works
someFunction('test'); // error
您可以将这些常量声明为类型:
// It's a good idea to export these types
// since you want them to be used external files
export type FIRST = "FIRST"
export type SECOND = "SECOND"
export type TOptions = FIRST | SECOND
// and then a call to your function will be
someFunction("FIRST") // ok
someFunction("SECOND") // ok
someFunction("THIRD") // Argument of type '"THIRD"' is not assignable to parameter of type 'TOptions'.(2345)
另一种选择是使用枚举类型:
export enum Options {
FIRST = 'FIRST',
SECOND = 'SECOND'
}
const otherFunction = (options: Options) => {}
otherFunction(Options.FIRST)
otherFunction(Options.SECOND)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.