2017-07-03 65 views
0

是否可以使用类型化函数从混合数组中检索特定类型?typescript - 使用类型化函数从混合数组返回特定​​类实例

public plugins: (Tool|Service)[] = []; 
getTools(): Tool[]{ 
    return this.plugins.filter(t => t instanceof Tool); 
} 

到目前为止我没有运气。 Typescript is throwing following message enter image description here

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); 
    } 
} 

回答

1

只是粘性。

public plugins: (Tool|Service)[] = []; 
getTools(): Tool[]{ 
    return this.plugins.filter(t => t instanceof Tool) as Tool[]; // << here 
} 

你需要做的,这是因为打字稿编译器是不是足够聪明,知道原因,当你做这样的过滤器它将只有返回Tool秒。 A .filter在任何阵列上都会通常返回与前一个阵列相同的类型,这就是编译器所假设的这里 - 一个Tool|Service数组。

编译器是足够聪明,知道,但是,一个Tool|Service可以降低到只有Tool秒 - 这样,你可以在年底做一个as Tool[]告诉编译器I know what I'm doing - the type that ".filter" returns will only be Tools here,编译器将听取和尊重它是这样的。

您可以在这里阅读更多关于as的关键字:https://www.typescriptlang.org/docs/handbook/basic-types.html(向下滚动或搜索“类型断言”)。

+0

没有打字2.4只是允许这个 - 返回类型作为推断目标(参见https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/) –

+0

' Array.map'绝对有效 - 'Array.filter'不会:c(即'plugins.map(a => a as Tool)'vs'plugins.filter(a =>一个工具实例)作为Tool []' ) –

+0

是的 - 你说得对。刚才试过了。 –