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:
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?
CodePudding user response:
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