简体   繁体   English

如何使用泛型实现类型声明?

[英]How to implement type declaration with generics?

How can I define a function which is an implementation of a type declaration that includes generics? 如何定义一个函数,该函数是包含泛型的类型声明的实现?

Here's what I mean: 这就是我的意思:

abstract class Base {}
class Sub extends Base {}

declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = <Sub>():Sub => new Sub();

console.debug(subFactory()); // expect instance of Sub

Unfortunately, this produces the following error: 不幸的是,这会产生以下错误:

Sub is not assignable to parameter of type Base

Can this be done? 能做到吗?

/edit nevermind, it actually works in Playground . / edit没关系,它实际上可以在Playground中使用 Guess it's a compiler version issue 猜猜这是编译器版本问题

This works: 这有效:

declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = (): Sub => new Sub();

let a = subFactory<Sub>(); // type of a is Sub

( code in playground ) 操场上的代码

But I'd do it like this: 但我会这样做:

declare type BaseFactory<T extends Base> = () => T;
let subFactory: BaseFactory<Sub> = (): Sub => new Sub();

let a = subFactory(); // type of a is Sub

( code in playground ) 操场上的代码


Edit 编辑

If you're using typescript >= 2.3 then you can use default generics: 如果您使用的打字稿> = 2.3,则可以使用默认的泛型:

declare type BaseFactory<T extends Base = Base> = () => T;

And then you don't need to specify T everywhere. 然后,您无需在所有地方都指定T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM