Skip to content

keyof erasure in generic union types #18990

@attatrol

Description

@attatrol

TypeScript Version: 2.2.2, 2.4.0

Code

interface A {
    a: number;
}

interface B extends A {
    b: number
}

export type IFieldConfig<TData> = { name: keyof TData };

export type TFieldConfigMap<TData> = {[P in keyof TData]: IFieldConfig<TData> & { name: P } };

let AFields: TFieldConfigMap<A> = {
    a: { name: 'a' }
};

let BFieldsFailed: TFieldConfigMap<B> = Object.assign({}, AFields, {
    b: { name: 'b' }
});

let BFieldsFailedToo: TFieldConfigMap<B> = Object.assign({}, AFields, {
    b: { name: <keyof B>'b' }
});

let BFieldsWorkaround: TFieldConfigMap<B> = Object.assign({}, AFields, {
    b: { name: <keyof Pick<B, 'b'>>'b' }
});

const BMap: {[P in keyof B]: P} = {
    a: 'a',
    b: 'b'
}

let BFieldsWorkaround2: TFieldConfigMap<B> = Object.assign({}, AFields, {
    b: { name: BMap.b }
});

Expected behavior:
compile flawlessly
Actual behavior:
failure to deduce types of both BFieldsFailed

Type 'TFieldConfigMap & { b: { name: string; }; }' is not assignable to type 'TFieldConfigMap'. Types of property 'b' are incompatible.
Type '{ name: string; }' is not assignable to type 'IFieldConfig & { name: "b"; }'.
Type '{ name: string; }' is not assignable to type 'IFieldConfig'.
Types of property 'name' are incompatible.
Type 'string' is not assignable to type '"a" | "b"'.

and BFieldsFailedToo

Type 'TFieldConfigMap & { b: { name: "a" | "b"; }; }' is not assignable to type 'TFieldConfigMap'.
Types of property 'b' are incompatible.
Type '{ name: "a" | "b"; }' is not assignable to type 'IFieldConfig & { name: "b"; }'.
Type '{ name: "a" | "b"; }' is not assignable to type '{ name: "b"; }'.
Types of property 'name' are incompatible.
Type '"a" | "b"' is not assignable to type '"b"'.
Type '"a"' is not assignable to type '"b"'.

I'm not sure if it is a bug in a second case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions