简体   繁体   English

TypeScript 在调用对象(它是一个函数)的值时未能推断出正确的类型

[英]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; }当没有调用返回值时,TypeScript 可以成功推断返回类型为() => { foo: number } ,但是当调用返回值时,类型推断扩展为{ foo: number; } | { bar: number; } { 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] .(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 } { foo: number } | { bar: number } . { foo: number } | { bar: number } Here the generic parameter doesn't affect it (already used to pre-evaluate the return type).这里泛型参数不影响它(已经用于预评估返回类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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