代码之家  ›  专栏  ›  技术社区  ›  Shannon Hochkins

元组与硬编码字符串

  •  0
  • Shannon Hochkins  · 技术社区  · 4 年前

    我们的工作中有这个代码,我想知道它和手动输入相同内容之间的区别。

    const tuple = <T extends string[]>(...args: T) => args;
    const strings = tuple(
      'blabla',
      'default',
      'standard'
    );
    
    export type Strings = typeof strings[number];
    
    

    当我把鼠标悬停在“字符串”上时,它基本上是 type Strings = 'blabla' | 'default' | 'standard'

    我的问题是,为什么不简单地输入相同的内容呢?

    type Strings = 'blabla' | 'default' | 'standard';
    

    而不是所有的元组?我看不出有什么不同,但如果有人能解释为什么我们要使用这个元组函数,那就太好了

    1 回复  |  直到 4 年前
        1
  •  1
  •   Oblosys    4 年前

    如果你不出口 strings 那么直接声明类型肯定更好。但在某些情况下,您还需要这些值,并使用它们 tuple 函数使您无需对每个函数指定两次。

    不过,有一种更简单、更安全的方法:

    export const strings = [ 'blabla', 'default', 'standard' ] as const;
    // type: readonly ["blabla", "default", "standard"]
    
    export type Strings = typeof strings[number]
    // type Strings = "blabla" | "default" | "standard"
    

    这使得 只读,所以你不能做一个不健全的 strings.pop() 例如

    TypeScript playground

    推荐文章