Issue with Angular's TypeScript Utility Type NestedKeyOf and Dotted Notation in Strict Mode

Discussão em 'Angular' iniciado por Sai Satwik Kuppili, Novembro 2, 2024.

  1. I'm working with Angular and using a custom TypeScript utility type NestedKeyOf to extract nested keys in a dotted notation format. The goal is for TypeScript to recognize nested properties as string literals in the format parent.child.

    Here's my NestedKeyOf type definition:

    type NestedKeyOf<T> = T extends object
    ? {
    [K in keyof T & string]: T[K] extends object
    ? K | `${K}.${NestedKeyOf<T[K]>}`
    : K;
    }[keyof T & string]
    : never;


    This type works as expected during Angular's compilation when "strict": false is set in angularCompilerOptions in tsConfig.json

    Example Code:

    Here's an example with the following types:

    export interface Node {
    name: string;
    version?: string;
    ip_address?: IPAddress;
    }

    export interface IPAddress {
    ipv4?: string;
    ipv6?: string;
    };


    And here's a method that uses NestedKeyOf:

    myMethod<K extends NestedKeyOf<Node>> (uiKey: K): string {
    return ''
    }

    temp = this.myMethod('ip_address.ipv');


    Issue:

    With "strict": false, Angular compiles without issues, and TypeScript recognizes invalid dotted notation and provides error messages, such as:

    ✘ [ERROR] TS2345: Argument of type '"ip_address.ip"' is not assignable to parameter of type '"name" | "version" | "ip_address" | "ip_address.ipv4" | "ip_address.ipv6"'. [plugin angular-compiler]


    However, when "strict": true is enabled, TypeScript fails to recognize dotted notation as valid and throws errors.

    ✘ [ERROR] TS2345: Argument of type '"ip_address.ipv4"' is not assignable to parameter of type '"name" | "version" | "ip_address"'. [plugin angular-compiler]


    Link to StackBlitz

    I've created a StackBlitz example to reproduce the issue.

    Question: Why does enabling strict mode cause TypeScript to stop recognizing the dotted notation format, and is there a way to get NestedKeyOf working with strict mode enabled?

    Continue reading...

Compartilhe esta Página