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 treating a object literal as a contract interface / type

I’m writing a test where I’m creating an object literal. For example:

const myObject = {
  id: 1,
  name: 'egg',
  error: null
}

The initialised value for myObject.error is null. However, when I try set it to a new value later on. For example:

myObject.error = ['exception', 'mapping']

I assign it a new value of string[] but I get 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

Type 'string[]' is not assignable to type 'null'.ts(2322)

myObject is not an interface or a type so why does it expect it to always be a null value?

Thanks!

>Solution :

That happens because you didn’t specifically define any other type for the myObject const, which will lead to TypeScript assigning the following type definition by default:

const myObject: {
    id: number;
    name: string;
    error: null;
}

Yeah, null is a TypeScript type, and obviously, string[] is not compatibale with that. You can however, define the type yourself, and make it compatible like so:

type ObjectType = {
    id: number;
    name: string;
    error: null | string[];
}

const myObject: ObjectType = {
  id: 1,
  name: 'egg',
  error: null
}

myObject.error = ['exception', 'mapping']

This way, you are letting TypeScript know, that myObject.error can either assume the null or string[] type values.

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