TypeScript array to string literal type

后端 未结 3 1521
迷失自我
迷失自我 2020-11-27 13:08

I currently have both an array of strings and a string literal union type containing the same strings:

const furniture = [\'chair\', \'table\', \'lamp\'];
ty         


        
3条回答
  •  没有蜡笔的小新
    2020-11-27 13:18

    This answer is out of date, see answer above.

    The best available workaround:

    const furnitureObj = { chair: 1, table: 1, lamp: 1 };
    type Furniture = keyof typeof furnitureObj;
    const furniture = Object.keys(furnitureObj) as Furniture[];
    

    Ideally we could do this:

    const furniture = ['chair', 'table', 'lamp'];
    type Furniture = typeof furniture[number];
    

    Unfortunately, today furniture is inferred as string[], which means Furniture is now also a string.

    We can enforce the typing as a literal with a manual annotation, but it brings back the duplication:

    const furniture = ["chair", "table", "lamp"] as ["chair", "table", "lamp"];
    type Furniture = typeof furniture[number];
    

    TypeScript issue #10195 tracks the ability to hint to TypeScript that the list should be inferred as a static tuple and not string[], so maybe in the future this will be possible.

提交回复
热议问题