TS1238:作为表达式调用时,无法解析类装饰器的签名

时间:2018-11-15 08:10:03

标签: typescript tsc typescript3.0

我看到以下编译错误:

  

TS1238:当被调用时,无法解析类装饰器的签名   表达式。

代码如下:

const a = [[
  'fun', 'legal', 'adventure',
], [
  'fun', 'legal', 'movie',
], [
  'fun', 'legal', 'm&m'
], [
  'fun', 'frowned upon', 'rec stuff'
], [
  'fun', 'frowned upon', 'religius views'
]];

let t = [];

const addLeaf = (array) => {
  if (!array || !array.length) return;

  let temp = { name: array[0], children: [] };

  if (array.length > 1) {
    temp.children = [addLeaf(array.slice(1))];
  }

  return temp;
};

const addToTree = (tree, array) => {
  if (!array || !array.length) return [];

  const branchIndex = tree.findIndex(entry => entry.name === array[0]);

  if (branchIndex !== -1) {
    tree[branchIndex].children = [...addToTree(tree[branchIndex].children, array.slice(1))];
  } else {
    tree = [...tree, addLeaf(array)];
  }

  return tree;
};

a.forEach((entry) => {
  t = addToTree(t, entry);
});

console.log(JSON.stringify(t, null, 2))

有人知道如何解决该错误吗?

1 个答案:

答案 0 :(得分:2)

类装饰器(您可以在lib.d.ts中找到)的签名必须为以下内容:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;

因此您的类装饰器不能具有fielddesc参数(或者,如果您还打算将装饰器用作字段装饰器,则它们应该是可选的)

const fdec = function (target: any) {
    console.log('target 0 :', target);
    target.bar = 3;
    return target;
};

const fdec2 = function () {
    console.log('target 1:');
    return function (target: any) {
        console.log('target 2:', target);
        target.bar = 3;
        return target;
    }
};

@fdec
@fdec2()
class Foo {
    static bar: number
}


console.log(Foo.bar);
console.log(new Foo());