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 TypeScript produce an error for this mapped type?

type JsonType<T> = {
  [P in keyof T as Exclude<P, "salt" | "hash">]: string;
};

type Test = {
  salt: string;
  hash: string;
};

const testObject: JsonType<Test> = {
  hash: "...",
  salt: "...",
};

why I’m not getting any error for defining an object named testObject of type JsonType<Test>? I excluded "salt" and "hash" from the type but I still can use them in an object when I expect them to be invalid.

I tried the code below but nothing has changed:

type JsonType<T> = {
  [P in Exclude<keyof T, "salt" | "hash">]: string;
};

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

>Solution :

First of all your JsonType<Test> will result in Record<never, string>, which is basically an object with no keys:

// never
type Keys = Exclude<keyof Test, 'salt' | 'hash'>

Since there is no strict type checking in the Typescript, in this case it allows you to assign additional properties to this variable without raising a type error, which is a design choice to avoid complex type dealing in other cases.

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