为什么扩展接口的泛型不能分配给匹配的对象?

Aro*_*ron 2 typescript

我收到此错误

[ts] Type '{ type: string; }' is not assignable to type 'A'.
Run Code Online (Sandbox Code Playgroud)

用下面的代码

interface Action {
    type: string;
}

function requestEntities<A extends Action>(type: string) {
    return function (): A {
        return { type };
    };
}
Run Code Online (Sandbox Code Playgroud)

为什么不能分配?Aextended Action,它只有一个属性:type,它是一个字符串。这是什么问题

A可能具有更多属性的问题吗?那我怎么告诉TypeScript A仍然只有该type: string属性而没有别的呢?

编辑

仅供参考,我要添加泛型A的原因是因为A它将具有特定的字符串作为type属性,例如{ string: 'FETCH_ITEMS' }

jca*_*alz 5

泛型在这里没有帮助您。如您所述,A可以具有更多属性:

interface SillyAction extends Action {
   sillinessFactor: number;
}
requestEntities<SillyAction>('silliness');
Run Code Online (Sandbox Code Playgroud)

在TypeScript中,通常没有办法说一个对象只有一组属性,因为TypeScript当前缺少确切的类型

但在您的情况下,您希望返回Action的对象type具有特定的 string;就像是:

interface SpecificAction<T extends string> extends Action {
   type: T;
}
function requestEntities<T extends string>(type: T) {
    return function (): SpecificAction<T> {
        return { type };
    };
}
requestEntities('silliness'); // returns a function returning {type: 'silliness'}
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助。祝好运!