I'm stilling learning the intricacies of typescript.
While trying to figure out Typescript: Generic to specific type , I came upon another situation I don't understand how Typescript is resolving.
export type GenericType = {
[key: string]: {
prop1: string,
prop2?: string,
prop3?: number,
}
};
const GoodObj: GenericType = {
key1: {
prop1: "hi",
// prop5: "what", // Type '{ prop1: string; prop5: string; }' is not assignable to type '{ prop1: string; prop2?: string; prop3?: number; }'.
},
key2: {
prop1: "bye",
prop2: "sup",
},
};
console.log(GoodObj);
const BadObj = {
key1: {
prop1: "hi",
prop5: "what",
},
key2: {
prop1: "bye",
prop2: "sup",
},
};
const BadObjGen: GenericType = BadObj;
console.log(BadObjGen);
In the above example, typescript will complain if I put an invalid prop into GoodObj
like I did to BadObj
. However, BadObj
doesn't complain when I assign an invalid obj to to BadObjGen
.
Yet, if I did the same thing with primitives, it does complain.
const type1: number = 1;
const type2: string = type1; // Type 'number' is not assignable to type 'string'
Under what circumstances does Typescript type check objects?
Codesandbox - https://codesandbox.io/s/typescript-experiment-hp92o?file=/src/index.ts:175-316