Skip to content

anything is assignable to T[P] where T extends null/undefined/void/object/never #15371

@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

case 1

export function test<T extends object, P extends keyof T>(
    whatever: T, name: P
): T[P] {
    const result = Math.random() > 0.5 ? whatever[name] : 'Hello!'; // <-- expected T[P] | string, actual T[P]
    return result; // <-- returning unsound result
}

case 2

export function oneOrAnother<A, B>(one: A, another: B): A | B {
    return Math.random() > 0.5 ? one : another;
}

export function test<T extends object, P extends keyof T>(
    whatever: T, name: P
): T[P] {
    const result = oneOrAnother(whatever[name], 'Hello!'); // <-- result is clearly string | T[P] as expected
    return result; // <-- expected a type error, actual returning string | T[P] instead of T[P] no problem
}

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions