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: string is assignable to {} Type

Why is this:

const test: {} = "test" // shouldn't this raise "Type 'string' is not assignable to type '{}'." error?
console.log(test)

A valid Typescript code?
Just a moment ago this bit of code caused me to send wrong API calls, because I had something like this:

const getAPIData = async (id: string, filters: NetworkFilters | {} = {})

What I wanted to achieve is the filters prop to have default value of object with no properties, but by my mistake I passed string there and this broke my API calls. Why is it possible? It should raise an error.

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 :

This is sadly one of the edge cases in TS where it’s probably a good idea to explain what assignable actually means.

{} is an object without properties, but as such, any object is assignable to it and string is not exception. (string also has methods f.e. toLowerCase).

If you for example declared const test: { toLowerCase: () => string } = "test", you will also not get an error, because toLowerCase is a method of string.

If you said const test: { notAStringMethod: () => string } = "test", then this fails, because notAStringMethod is not a method of string and thus isn’t assignable.

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