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

时间:2017-08-01 14:02:17

标签: typescript

我收到此错误

.rptdesing

使用以下代码

[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,它只有一个属性:Action,这是一个字符串。这里的问题是什么?

问题是type可能有更多属性吗?那么我如何告诉TypeScript A仍然只有A属性而没有别的?

编辑

仅供参考我想要添加通用type: string的原因是因为A将具有特定的字符串作为类型属性,例如A

3 个答案:

答案 0 :(得分:5)

通用并不能帮到你。如您所知,A可以包含更多属性:

interface SillyAction extends Action {
   sillinessFactor: number;
}
requestEntities<SillyAction>('silliness');

在TypeScript中通常没有办法说对象只有 某些属性集,因为TypeScript目前缺少exact types

但在您的情况下,您希望返回的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'}

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

答案 1 :(得分:2)

  

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

因为您确定AAction兼容,所以您可以放心编译器:

return { type } as A;

答案 2 :(得分:0)

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

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')

Shows error:

相关问题