TypeScript array to string literal type

后端 未结 3 1518
迷失自我
迷失自我 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:23

    The only adjustement I would suggest is to make the const guaranteed compatible with the type, like this:

    type Furniture = 'chair' | 'table' | 'lamp';
    
    const furniture: Furniture[] = ['chair', 'table', 'lamp'];
    

    This will give you a warning should you make a spelling error in the array, or add an unknown item:

    // Warning: Type 'unknown' is not assignable to furniture
    const furniture: Furniture[] = ['chair', 'table', 'lamp', 'unknown'];
    

    The only case this wouldn't help you with is where the array didn't contain one of the values.

提交回复
热议问题