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
可能具有更多属性?那么如何告诉TypeScriptA
仍然只有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')