Checking if a value is valid for a union type

前端 未结 2 928
闹比i
闹比i 2020-12-04 03:36

Suppose I have this type defined in my app:

type PiiType = \'name\' | \'address\' | \'email\';

I u

2条回答
  •  醉话见心
    2020-12-04 04:21

    The trick is to run the array through an identity function that infers an element type constrained by string. That will cause the compiler to infer a union of literal types:

    function asLiterals(arr: T[]): T[] { return arr; }
    const piiTypeValues = asLiterals(['name', 'address', 'email']);
    type PiiType = (typeof piiTypeValues)[number];
    

    There's another solution here but the above seems a bit simpler.

提交回复
热议问题