Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 为什么扩展接口的泛型类型不能分配给匹配的对象?_Typescript - Fatal编程技术网

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

Typescript 为什么扩展接口的泛型类型不能分配给匹配的对象?,typescript,Typescript,我得到了这个错误 [ts] Type '{ type: string; }' is not assignable to type 'A'. 用下面的代码 interface Action { type: string; } function requestEntities<A extends Action>(type: string) { return function (): A { return { type }; }; } 接口动作

我得到了这个错误

[ts] Type '{ type: string; }' is not assignable to type 'A'.
用下面的代码

interface Action {
    type: string;
}

function requestEntities<A extends Action>(type: string) {
    return function (): A {
        return { type };
    };
}
接口动作{
类型:字符串;
}
函数请求实体(类型:字符串){
返回函数():A{
返回{type};
};
}
为什么它不可分配<代码>一个扩展了
操作
,它只有一个属性:
类型
,它是一个字符串。这里有什么问题

问题是
A
可能具有更多属性?那么如何告诉TypeScript
A
仍然只有
type:string
属性而没有其他属性

编辑


仅供参考,我想添加泛型
A
的原因是
A
将有一个特定的字符串作为类型属性,例如
{string:'FETCH_ITEMS'}
泛型在这里没有帮助。正如您所注意到的,
A
可以具有更多属性:

interface SillyAction extends Action {
   sillinessFactor: number;
}
requestEntities<SillyAction>('silliness');
希望有帮助。祝你好运

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

因为您确信
A
操作
兼容,所以您可以向编译器保证:

return { type } as A;

看看你可以做什么,以实现更强的类型安全性 (我没有完全理解您的任务,但从这个示例中应该可以清楚地看到方法)

接口动作{
类型:字符串;
金额:数字;
}
const action:action={type:'type1',amount:123}
函数请求实体(类型:键){
返回操作[类型]
}
请求实体('类型')
请求实体(“金额”)
requestEntities('random-stuff')

return { type } as A;
interface Action {
    type: string;
    amount: number;
}

const action: Action = { type: 'type1', amount: 123 }

function requestEntities<KEY extends keyof Action>(type: KEY) {
    return action[type]
}

requestEntities('type')
requestEntities('amount')

requestEntities('random-stuff')