【问题标题】:Use const values as union type options Typescript使用 const 值作为联合类型选项
【发布时间】:2020-10-26 10:55:31
【问题描述】:

考虑这个例子:

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 值作为类型联合选项。

我该怎么做?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    我相信您需要使用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
    

    Playground Link

    【讨论】:

    • this link 帮助我澄清您在 Typescript 中对typeof 运算符的回答和用法。
    【解决方案2】:

    您可以将这些常量声明为类型:

    // 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 2020-04-02
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2019-11-26
      相关资源
      最近更新 更多