Home > Mobile >  Typescript does not want to spread type that's object by exclusion
Typescript does not want to spread type that's object by exclusion

Time:08-09

I'm having issues spreading an externally imported type that's an object by way of Exclude. To demonstrate:

const f = (): object => ({});
const v = {...f()}; // valid -> OK
const f = (): object | string => ({});
const v = {...f()}; // invalid -> OK
const f = (): Exclude<object | string, "string"> => ({});
const v = {...f()}; // invalid -> PROBLEM

In the last snippet I would expect the Exclude to make the type valid. Is this me thinking about it wrongly, or is there another way of fixing this? (the type exemplified by object is an external import I can't change).

CodePudding user response:

You made a typo in the exclude : You want to exclude the type string not the type "string" (which is a string that can only have the value "string")

const f = (): Exclude<object | string, string> => ({});
const v = { ...f2() }; // ok

Playground

  • Related