0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And there is no way to get that repetition out, right?
@Twiggeh If you use myType<T> as a parameter of a function, then you can make type inference do the job. But if you're defining a property, variable, etc. you'll have to specify the type explicitly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.