typescript - Fel i rekursiv mappad typ upptäcks inte. Varför?


Se koden nedan eller motsvarande playground:

type SomeType = {
  [P in 'u']?: string;
} & {
  [P in 'a' | 'b' | 'c' | 'd']?: SomeType;
}

const st: SomeType = {
  u: '1',
  a: {
    u: '2',
    b: {
      u: '3',
      c: {
        d: {
        },
        e: 1, // why doesn't this cause an error here? oO thank you!
      }
    },
  },
  e: 1, // expected error: Object literal may only specify known properties, and 'e' does not exist in type 'SomeType'.
};

Jag vet inte vad mer jag ska säga här. Om du kommenterar ut den senaste e: 1 så genereras ingen ts-fel. Varför?

Redigera: Okej, typ vad fan.

type SomeType = {
  u?: string;
  a?: SomeType;
  b?: SomeType;
  c?: SomeType;
  d?: SomeType;
}

const st: SomeType = {
  u: '1',
  a: {
    u: '2',
    b: {
      u: '3',
      c: {
        d: {
        },
        e: 1, // expected error: Object literal may only specify known properties, and 'e' does not exist in type 'SomeType'.
      }
    },
  },
  e: 1, // expected error: Object literal may only specify known properties, and 'e' does not exist in type 'SomeType'.
};

Redigera: Här är den fixade versionen jag skapade med råden från @tokland att rekursion med snitt är trasig.

type P = 'u';
type Q = 'a' | 'b' | 'c' | 'd';

type SomeType = {
  [K in (P | Q)]?: K extends P
    ? string
    : SomeType
};

const st: SomeType = {
  u: '1',
  a: {
    u: '2',
    b: {
      u: '3',
      c: {
        d: {
        },
        e: 1, // expected error: Object literal may only specify known properties, and 'e' does not exist in type 'SomeType'.
      }
    },
  },
  e: 1, // expected error: Object literal may only specify known properties, and 'e' does not exist in type 'SomeType'.
};

Svar #1

Det är en känd bugg, kontroll av överflödiga egenskaper för nästlade typintersektioner fungerade bra fram till 3.8:

https://github.com/microsoft/TypeScript/issues/47935

3.8: arbetar

3.9: fungerar inte