简体   繁体   English

Typescript装饰器欺骗2个参数,如何编译?

[英]Typescript decorator deceiving 2 arguments, how to compile this?

I've been reading up more about decorators in typescript and ES7. 我一直在阅读有关打字稿和ES7中的装饰器的更多信息。 And I tried this simple code: 我尝试了以下简单代码:

function decorator(...args) {
    console.log(args);
}

//@decorator
class foo {
    constructor() {}

    @decorator
    method() {}
}

let bar = new foo();
bar.method();

This is what I get in the console: 这是我在控制台中得到的:

$ npm install -g typescript@2.1.15
$ npm install -g @types/node
$ tsc --experimentalDecorators file.ts
$ node file.js
[ foo { method: [Function] }, 'method' ]

Only two arguments. 只有两个参数。

However if I execute this in the typescript playground, I have this result 但是,如果我在打字稿游乐场执行此操作,则会得到此结果

Array[3]

Where Arra[0] and Array[2] are Objects and Array[1] is a string. 其中Arra [0]和Array [2]是对象,而Array [1]是字符串。

How this is possible? 这怎么可能? Furthermore, how should I properly compile typescript with the experimental decorators? 此外,我应该如何使用实验装饰器正确编译打字稿?

My best regards... 我最诚挚的问候...

Solved. 解决了。 According to https://www.typescriptlang.org/docs/handbook/compiler-options.html the default target is ES3. 根据https://www.typescriptlang.org/docs/handbook/compiler-options.html ,默认目标是ES3。

Setting the target to ES5 solves the problem: 将目标设置为ES5可解决以下问题:

$ tsc --experimentalDecorators -t 'es5' t.ts && node t.js
[ foo { method: [Function] },
  'method',
  { value: [Function],
    writable: true,
    enumerable: true,
    configurable: true } ]

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM