【问题标题】:Can I remove `typeof` operator in type我可以删除类型中的 `typeof` 运算符吗
【发布时间】: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&lt;A&gt;,但这仅适用于类构造函数;见examples。你能解释一下具体的用例吗?仅适用于类构造函数吗?
  • 也许你的用例是:Record&lt;string, U extends A&gt;?
  • 我不明白你的新用例; exampleFn1 不能真正工作,因为v 将是一个类实例而不是构造函数。你的exampleFn2 工作正常,虽然我可能会在这里说new () =&gt; A 而不是typeof A(比如this)。但在这两种情况下,InstanceType&lt;typeof A&gt; 在这里都没有多大帮助。具体是什么问题?你能用两个词和minimal reproducible example来描述它吗?

标签: typescript


【解决方案1】:

使用InstanceType:

type B = InstanceType<A>;

或者干脆

type B = A["prototype"];

Demo link

【讨论】:

  • 哦,谢谢一百万。我编辑了确切的用例,有没有更好的方法来实现它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多