Skip to content

Compile Error when using generic type with [K in keyof T]?: XXX  #31070

@shaunxu

Description

@shaunxu

TypeScript Version: 3.4.4

Search Terms:
keyof index-properties generic-type

Code

type Numeric<T> = {
    [K in keyof T]?: number
}

class Entity {
    aNumber: number;
}

const fn = <T extends Entity>() => {
    const n: Numeric<T> = {
// .      ^
// .      Type '{ aNumber: number; }' is not assignable to type 'Numeric<T>'
        aNumber: 1
    };
};

Expected behavior:
Should not report compile error since in the type constraint of function fn was <T extends Entity> which means T should have aNumber: number and { aNumber: 1 } should be satisfied.

Actual behavior:
Compile error said Type '{ aNumber: number; }' is not assignable to type 'Numeric<T>'.

Playground Link:
https://www.typescriptlang.org/play/index.html#src=type%20Numeric%3CT%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BK%20in%20keyof%20T%5D%3F%3A%20number%0D%0A%7D%0D%0A%0D%0Aclass%20Entity%20%7B%0D%0A%20%20%20%20aNumber%3A%20number%3B%0D%0A%7D%0D%0A%0D%0Aconst%20fn%20%3D%20%3CT%20extends%20Entity%3E()%20%3D%3E%20%7B%0D%0A%20%20%20%20const%20n%3A%20Numeric%3CT%3E%20%3D%20%7B%0D%0A%2F%2F%20.%20%20%20%20%20%20%5E%0D%0A%2F%2F%20.%20%20%20%20%20%20Type%20'%7B%20aNumber%3A%20number%3B%20%7D'%20is%20not%20assignable%20to%20type%20'Numeric%3CT%3E'%0D%0A%20%20%20%20%20%20%20%20aNumber%3A%201%0D%0A%20%20%20%20%7D%3B%0D%0A%7D%3B

Related Issues:
https://stackoverflow.com/questions/55804034/keyof-reported-compile-error-when-using-generic-type

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: Mapped TypesThe issue relates to mapped types

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions