简体   繁体   English

通过typescript 3.0通用rest元组类型从类tuple返回实例元组

[英]return instance tuple from classes tuple via typescript 3.0 generic rest tuples type

While getting proper instance type from class type works like following: 从类类型获取正确的实例类型时,其工作方式如下:

type Constructor<T = {}> = new (...args: any[]) => T

class Foo {}

function getInstanceFromClass<T>(Klass: Constructor<T>): T {
  return new Klass()
}

// $ExpectType Foo
const fooInst = getInstanceFromClass(Foo)

I didn't figure out how to get proper instance type with new TS 3.0 feature ( Generic rest parameters ) 我没有弄清楚如何通过新的TS 3.0功能(常规的rest参数)获得正确的实例类型。

class Foo {}
class Test {}

function getInstancesFromClasses<T extends Constructor[]>(...klasses: T): T { 
  return klasses.map(klass => new klass()) as any
}

// $ExpectType [typeof Foo, typeof Test]
const instances = getInstancesFromClasses(Foo,Test)

but what I need is 
// $ExpectType [Foo, Test]

We can get this to mostly work on 3.0, but for full tuple mapping support we will need to wait for 3.1. 我们可以使它主要在3.0上运行,但是要获得完整的元组映射支持,我们将需要等待3.1。

To extract the result tuple type we can use a mapped and a conditional type to extract the result type from the Constructor[] . 为了提取结果元组类型,我们可以使用映射类型和条件类型从Constructor[]提取结果类型。 This almost works in 3.0. 这几乎可以在3.0中使用。 In 3.0 the mapped type will mangle the array type so that only indexing operations will still be OK on the resulting type, all methods will be of type never. 在3.0中,映射类型将破坏数组类型,以便仅索引操作在结果类型上仍然可以,所有方法的类型都从不。 3.1 will make mapped types on tuples and arrays work more as expected (read PR for details) . 3.1将使元组和数组上的映射类型按预期工作得更多(有关详细信息,请阅读PR )。

type Constructor<T = {}> = new (...args: any[]) => T

class Foo {}
class Test {}

type InstanceTypes<T> = {
    [P in keyof T] :T[P] extends Constructor<infer U> ? U : never
}

function getInstancesFromClasses<T extends Constructor[]>(...klasses: T): InstanceTypes<T> { 
return klasses.map(klass => new klass()) as any
}

const instances = getInstancesFromClasses(Foo,Test)
let foo = instances[0] // is Foo
let bar = instances[1] // is Test

let [foo1, bar2] = instances // error in 3.0 since the mapped type is not really a tuple will work in 3.1

Note You can already test that this works fully in 3.1 by installing from npm ( npm install typescript@next ). 注意通过从npm install typescript@nextnpm install typescript@next ),您已经可以测试它在3.1中是否可以完全正常工作。 3.1 is due for release sometime before the end of august 2018 3.1将于2018年8月底之前的某个时间发布

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

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