Home > Software engineering >  Typescript: string is assignable to {} Type
Typescript: string is assignable to {} Type

Time:08-31

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.

CodePudding user response:

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.

  • Related