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;
};

>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.

Leave a Reply