Home > Net >  Typescript: number type can be assigned to string type using Omit, Optional, Intersection Types
Typescript: number type can be assigned to string type using Omit, Optional, Intersection Types

Time:07-24

Could you please tell me why the following code does not cause an error?

Playground Link

type NumberType = {
  field?: { id: string; numberOrString?: number }
};
type StringType = Omit<NumberType, "field"> & {
  field?: { id: string } & { numberOrString?: string }
};

const test = (s: StringType) => {
  // `numberOrString?: number` can be assigned to `numberOrString?: string`
  const n: NumberType = s; // no error
};

CodePudding user response:

This is a known bug in TypeScript, see microsoft/TypeScript#19927.

Your Omit<NumberType, "field"> type evaluates to the equivalent of {[K in never]: ...}, and apparently intersections of such never-keyed mapped types and other object types with optional properties are not checked correctly. This bug has been open for a long time so it's not clear when or even if it will be fixed; presumably people don't run into it very often? If you care a lot you might want to give that issue a

  • Related