Skip to content

函数参数有展开符号(...)时编译会报错 #109

@l5oo00

Description

@l5oo00

开发时命中了一个诡异的 bug, 调用 ts2php 编译 ts 文件时会报错:

src/index.ts:3:11 - error TS2554: Expected 0 arguments, but got 1.

3 debug.log('xxx');
            ~~~~~

目录结构如下:

├── build.js
├── package.json
└── src
    ├── deps.ts
    └── index.ts

各个文件内容如下:

  • build.js
const ts2php_1 = require("ts2php");
const fs_extra_1 = require("fs");
let compiler;
function ts2php(filePath) {
    // @note 复现必选条件1:  compiler 必须缓存
    if (!compiler) {
        compiler = new ts2php_1.Ts2Php();
    }

    const options = {};
    options.source = fs_extra_1.readFileSync(filePath, 'utf8');
    const {phpCode} = compiler.compile(filePath, options);
    return phpCode;
}


// @note 复现必选条件2:  必选先是 deps.ts , 然后是 index.ts
ts2php('./src/deps.ts');
ts2php('./src/index.ts');
// ts2php('./src/deps.ts');
  • package.json
{
  "dependencies": {
    "ts2php": "0.19.13",
    "typescript": "3.4.5"
  }
}
  • src/deps.ts
class Debug {
    log(msg: any = '', ...args: any[]) {
        args.unshift(msg);

        // @note 复现必选条件3:  函数体里必须没有出现过 ...args, 放开下面一行注释就不会有问题, 仅限于 [email protected][email protected] 版本下,无论开不开下面的注释,都会报错
        // console.log(...args);
    }
}
export function makeDebug(name = '') {
    return new Debug();
}
  • src/index.ts
import {makeDebug} from './deps';
const debug = makeDebug('yldebug');
debug.log('xxx');

安装依赖(npm i)后,执行 node build.js 复现问题。

目前发现复现问题有三个前置条件, 具体见上面代码里的注释 @note 复现必选条件

临时的 trick 方案就是根据复现条件3得来的, 将 args 赋值给另一个变量 const argsX = [...args];即可。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions