【问题标题】:TypeScript compiler API: Print generic constraint with checker.typeToString()TypeScript 编译器 API:使用 checker.typeToString() 打印通用约束
【发布时间】:2018-06-12 16:10:26
【问题描述】:

是否可以使用checker.typeToString() 来打印泛型类型约束?

class Item {}
class Container<T extends Item> {
  public item: T;
}

const type = checker.getTypeAtLocation( /** AST node of 'item' property */ );
checker.typeToString( type ); // returns 'T'

我想查看返回值'Item'TypeFormatFlags 似乎都没有涵盖这一点。

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    没有办法直接获取类型和约束。您可以获得泛型类型的约束,您可以打印约束的类型并将其与extends 关键字放在一起会得到您想要的。

    const type = checker.getTypeAtLocation( paramNode );
    let constraintType = type.getConstraint();
    if(constraintType == null) continue;
    let genericType = checker.typeToString(type); // T 
    let genericConstraintType = checker.typeToString(constraintType);  // Item
    console.log(`${genericType} extends ${genericConstraintType}`); // put it together manually 
    

    【讨论】:

      猜你喜欢
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2020-02-28
      • 1970-01-01
      • 2018-07-27
      • 2021-01-25
      • 1970-01-01
      相关资源
      最近更新 更多