Home > Software design >  typescript conditional type on generic
typescript conditional type on generic

Time:10-17

I have a type in a shape like this (simplified):

type AllContentType =
    | 'application/json'
    | 'application/octet-stream'
    | 'multipart/form-data';

type myType<T = AllContentType> = {
    body: T extends 'multipart/form-data' ? number : string;
    otherHeader: T;
};

and it cannot figure out which string has been put into otherHeader, it always returns


const obj: myType = { header: 'multipart/form-data', body: ""  };

body as string | number. Any way to get it to figure out what I actually have put in?

TSPlayground

CodePudding user response:

By giving your type parameter a default value

type myType<T = AllContentType>

writing this

const obj: myType = { otherHeader: 'multipart/form-data', body: ""  };

is effectively

const obj: myType<AllContentType> = { otherHeader: 'multipart/form-data', body: ""  };

which makes the predicate T extends 'multipart/form-data' false.

If you leave out the default value for the type parameter and specify the type explicitly, it would work properly:

type myType<T extends AllContentType> = {
  body: T extends 'multipart/form-data' ? number : string;
  otherHeader: T;
};

const obj: myType<'multipart/form-data'> = { otherHeader: 'multipart/form-data', body: "" };

although that adds repetition.

  • Related