是否可以使用类型化函数从混合数组中检索特定类型?typescript - 使用类型化函数从混合数组返回特定类实例
public plugins: (Tool|Service)[] = [];
getTools(): Tool[]{
return this.plugins.filter(t => t instanceof Tool);
}
到目前为止我没有运气。 Typescript is throwing following message
TS2322:类型'(Tool | Service)[]'不能分配给'Tool []'类型。 Property'onclick'在类型'Service'中缺失。
有没有办法在这里设置功能类型为Tool[]
?
这里是全码:上as Tool[]
末
interface Required {
id: string
title: string
owner: string
type: 'user' | 'admin'
}
class P {
id; title; owner; type;
constructor(config: Required){
this.id = config.id || 'uniqid';
this.title = config.title || 'Title';
this.owner = config.owner || 'user';
this.type = config.type;
}
}
interface ToolRequired extends Required{
onclick:() => void
}
class Tool extends P {
onclick;
constructor(config = {} as ToolRequired){
super(config);
this.type = 'tool';
this.onclick = config.onclick
}
}
class Service extends P {
constructor(config = {} as Required){
super(config);
this.type = 'service'
}
}
class Storag {
static types = {
tool: Tool,
service: Service,
undefined: Tool,
};
public plugins: (Tool|Service)[] = [];
setPlugin(config = {} as Required){
const Type = Storag.types[config.type];
this.plugins.push(new Type(config));
}
getTools(): Tool[]{
return this.plugins.filter(t => t instanceof Tool);
}
}
没有打字2.4只是允许这个 - 返回类型作为推断目标(参见https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/) –
' Array.map'绝对有效 - 'Array.filter'不会:c(即'plugins.map(a => a as Tool)'vs'plugins.filter(a =>一个工具实例)作为Tool []' ) –
是的 - 你说得对。刚才试过了。 –