简体   繁体   中英

TypeScript failed to infer the correct type when calling the value of object (which is a function)

const record = {
    foo: () => ({ foo: 1 }),
    bar: () => ({ bar: 1 }),
}

function getRecord<T extends keyof typeof record>(type: T) {
    return record[type];
}

const obj = getRecord(`foo`);
// if line 7 is:        return record[type];
// typeof obj will be:  () => { foo: number; }

// but if line 7 is:    return record[type]();
// typeof obj will be:  { foo: number; } | { bar: number; }
obj

Playground link

When the return value is not called, TypeScript can successfully infer the return type to be () => { foo: number } , but when the return value is called, the type inference broadened to { foo: number; } | { bar: number; } { foo: number; } | { bar: number; } { foo: number; } | { bar: number; } . Why is this happening?

The return type of:

function getRecord<T extends keyof typeof record>(type: T) {
    return record[type];
}

Is (typeof record)[T] . As you can see, the generic type parameter influences the return type of the function when function is called.


In the second example:

function getRecord<T extends keyof typeof record>(type: T) {
    return record[type]();
}

The return type is { foo: number } | { bar: number } { foo: number } | { bar: number } . Here the generic parameter doesn't affect it (already used to pre-evaluate the return type).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM