【问题标题】:Typescript compiler API: print PropertySignature on a single lineTypescript 编译器 API:在一行上打印 PropertySignature
【发布时间】:2019-03-27 01:41:10
【问题描述】:

我正在尝试生成一个返回对象文字类型的函数(不确定这是否是正确的术语)。我目前使用以下:

ts.createFunctionDeclaration(
    undefined, //decorators
    [], //modifiers
    undefined, //asterisk
    'foo',
    undefined, //name
    [], //parameters

    ts.createTypeLiteralNode( //return type
        [
            ts.createPropertySignature(
                undefined, //modifiers
                ts.createIdentifier('bar'),
                undefined, //question token
                ts.createTypeReferenceNode(
                    'string',
                    undefined //generics
                ),
                undefined //initializer
            ),
            ts.createPropertySignature(
                undefined, //modifiers
                ts.createIdentifier('baz'),
                undefined, //question token
                ts.createTypeReferenceNode(
                    'string',
                    undefined //generics
                ),
                undefined //initializer
            )
        ]
    ),

    ts.createBlock([
        //some interesting statements
    ])
);

这会生成以下代码:

function foo(): {
    bar: string;
    baz: string;
} {
    //interesting statements
}

它有效,但我希望返回类型文字位于这样的一行中:

function foo(): { bar: string, baz: string } {
    //interesting statements
}

这是否可以仅使用 Typescript 编译器 API,还是我需要使用外部 linter/formatter?

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    尝试在类型文字节点上设置发射标志EmitFlags.SingleLine

    const typeLiteralNode = ts.createTypeLiteralNode(...);
    ts.setEmitFlags(typeLiteralNode, EmitFlags.SingleLine);
    

    emitter.ts 中的emitTypeLiteral 似乎表明可以这样做。

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 2012-10-24
      • 2020-05-26
      • 2019-09-18
      • 2011-03-21
      相关资源
      最近更新 更多