2017-08-01 24 views
0

我收到此错误为什么扩展接口不能分配给匹配对象的泛型类型?

[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,这是一个字符串。这里有什么问题?

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

编辑

仅供参考,我想添加的通用A是因为A将有特定 string类型属性,例如原因{ string: 'FETCH_ITEMS' }

回答

2

通用不帮你在这里。当你注意,A可以有更多的属性:

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

有一般不打字稿的方式说一个对象有只有一些属性集,因为打字稿目前缺乏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'} 

希望有帮助。祝你好运!

2

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

因为你确信AAction兼容,你可以放心的编译器:

return { type } as A; 
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:

相关问题