Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading