相关疑难解决方法(0)

如何实现打字稿装饰器?

TypeScript 1.5现在有装饰器.

有人可以提供一个简单的例子来演示实现装饰器的正确方法,并描述可能的有效装饰器签名中的参数是什么意思吗?

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
Run Code Online (Sandbox Code Playgroud)

另外,在实现装饰器时是否应该记住哪些最佳实践注意事项?

decorator typescript

198
推荐指数
3
解决办法
7万
查看次数

TypeScript装饰器报告"当作为表达式调用时无法解析类装饰器的签名"

@xxx("xxx")
class A{
    msg:string
    constructor(msg:string) {
        this.msg = msg
    }
    print() {
        console.log(this.msg)
    }
}

function xxx(arg:string) {
    function f(target) {
        function ff(msg: string) {
            return new target(arg + ":" + msg)
        }
        return ff
    }
    return f
}

let a = new A("hellow")
a.print()
Run Code Online (Sandbox Code Playgroud)

编译时,报告:

decorator.ts(1,1):错误TS1238:当作为表达式调用时,无法解析类装饰器的签名.类型'(msg:string)=> any'不能分配给'void'类型.

但是生成的js执行得很好.我不知道为什么报错.

typescript

36
推荐指数
7
解决办法
4万
查看次数

将JSON.stringify与TypeScript getter/setter结合使用

我在TypeScript中使用getter/setter访问器.由于变量和方法不可能具有相同的名称,因此我开始使用较低的短划线为变量添加前缀,如许多示例所示:

private _major: number;

get major(): number {
  return this._major;
}
set major(major: number) {
  this._major = major;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我使用JSON.stringify()方法将对象转换为JSON字符串时,它将使用变量名作为键:_major.

由于我不希望JSON文件的所有键都以下划线作为前缀,因此有可能使TypeScript使用getter方法的名称(如果可用)吗?或者是否有其他方法可以使用getter/setter方法,但仍然可以生成干净的JSON输出?

我知道有些方法可以在将JSON密钥写入字符串输出之前手动修改它们.如果有更简单的解决方案,我很好奇.

这是一个JSFiddle,它演示了当前的行为.

json getter-setter typescript

12
推荐指数
3
解决办法
6012
查看次数

标签 统计

typescript ×3

decorator ×1

getter-setter ×1

json ×1