【发布时间】:2022-01-05 01:54:32
【问题描述】:
我有一个关于类型操作的问题
class A {}
class B extends A {}
class C extends A {}
function exampleFn1<T extends Record<string, A>>( t: T ) {
for( const v of Object.values( t ) )
new v(); // TS2351: This expression is not constructable.
// Type 'A' has no construct signatures.
}
function exampleFn2<T extends Record<string, typeof A>>( t: T ) {
for( const v of Object.values( t ) )
new v(); // ok
}
虽然第二种方法没有报错,但是我想得到A而不是typeof A,怎么办
type A = typeof Example;
type B = RemoveTypeof<A>; // Expect type B = Example
【问题讨论】:
-
你能说清楚一点吗
-
没有“删除
typeof”这样的操作符,它甚至不是特别明智,请参阅this rant/answer 解释typeof操作符。你可以写type B = InstanceType<A>,但这仅适用于类构造函数;见examples。你能解释一下具体的用例吗?仅适用于类构造函数吗? -
也许你的用例是:
Record<string, U extends A>? -
我不明白你的新用例;
exampleFn1不能真正工作,因为v将是一个类实例而不是构造函数。你的exampleFn2工作正常,虽然我可能会在这里说new () => A而不是typeof A(比如this)。但在这两种情况下,InstanceType<typeof A>在这里都没有多大帮助。具体是什么问题?你能用两个词和minimal reproducible example来描述它吗?
标签: typescript