TypeScript require one parameter or the other, but not neither

前端 未结 4 512
不思量自难忘°
不思量自难忘° 2021-01-04 01:50

Say I have this type:

export interface Opts {
  paths?: string | Array,
  path?: string | Array

        
4条回答
  •  别那么骄傲
    2021-01-04 02:14

    This works.

    It accepts a generic type T, in your case a string.

    The generic type OneOrMore defines either 1 of T or an array of T.

    Your generic input object type Opts is either an object with either a key path of OneOrMore, or a key paths of OneOrMore. Although not really necessary, I made it explicit with that the only other option is never acceptable.

    type OneOrMore = T | T[];
    
    export type Opts = { path: OneOrMore } | { paths: OneOrMore } | never;
    
    export const foo = (o: Opts) => {};
    
    foo({});
    

    There is an error with {}

提交回复
热议问题