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

Why doesn't my TypeScript interface alert me that it is missing some properties?

I have a TypeScript interface with required properties.

But when typing an object and pushing it into an array there is no error message alerting me that some of the required properties are missing.

Here is an example from my code:

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

interface Keyword {
  keyword: string;
  language: string;
  location: string;
  searchEngineDomain: string;
  organicPositionLastThirtyDays: number[];
  createdAt: string;
}

const keywords = [];
keywords.push({
    keyword: 'My First Keyword',
} as Keyword);

I was expecting to see an error telling me the object I am pushing into the array is missing five required properties. But I see no error at all.

Why does this happen?

>Solution :

It’s because keywords is of type any[], while it should be Keyword[]. You should also remove as Keyword as it kinda means "believe me, it’s all we want here". Type assertions can hide type errors.

Check out the following snippet:

interface Keyword {
  keyword: string;
  language: string;
  location: string;
  searchEngineDomain: string;
  organicPositionLastThirtyDays: number[];
  createdAt: string;
}

const keywords: Keyword[] = [];
keywords.push({
    keyword: 'My First Keyword',
});

You will receive the following error:

Argument of type ‘{ keyword: string; }’ is not assignable to parameter
of type ‘Keyword’. Type ‘{ keyword: string; }’ is missing the
following properties from type ‘Keyword’: language, location,
searchEngineDomain, organicPositionLastThirtyDays, createdAt

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