考虑以下示例:
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
值作为类型联合选项。
我该怎么做?
答案 0 :(得分:2)
我相信您需要使用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
答案 1 :(得分:1)
您可以将这些常量声明为类型:
// 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)