Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何声明一个方法?_Typescript - Fatal编程技术网

Typescript 如何声明一个方法?

Typescript 如何声明一个方法?,typescript,Typescript,我有一个属性装饰器,它在类上生成一些方法。如何获取有关这些的键入信息 class Foo { @GenerateGetterAndSetter() _bar: string; // How to do the following: declare public bar(): string; declare public bar(value: string): this: } let foo = new Foo(); foo.bar(); 我得到的错误是TS1031:“decl

我有一个属性装饰器,它在类上生成一些方法。如何获取有关这些的键入信息

class Foo {
  @GenerateGetterAndSetter() _bar: string;
  // How to do the following:
  declare public bar(): string;
  declare public bar(value: string): this:
}

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

我得到的错误是TS1031:“declare”修饰符不能出现在类元素上

您不能对非环境定义使用
declare

但是,您可以使用混合中使用的相同技巧:

class Foo {
    @GenerateGetterAndSetter() _bar: string;

    public getBar: () => string;
    public setBar: (value: string) => this;
}
正如书中所写:

为了满足这一要求,我们创建了代理属性及其 来自我们的mixin的成员的类型。这就满足了 编译器提示这些成员在运行时可用

我使用了
getBar
setBar
,因为您不能重用方法的名称,除非您:

class Foo {
    @GenerateGetterAndSetter() _bar: string;

    public get bar(): string {
        return null;
    }

    public set bar(value: string) {}
}
在这种情况下,您必须有虚拟实现,然后可以使用装饰器覆盖这些实现。
但使用setter时,您不能返回任何内容,如果您尝试,您将得到:

“set”访问器不能具有返回类型批注


编辑 根据您关于实现只有一个方法的评论,您将无法使用“替代属性”,因为它不允许使用两个不同的签名:

class Foo {
    @GenerateGetterAndSetter() _bar: string;

    public bar: () => string;
    public bar: (value: string) => this; // error: Duplicate identifier 'bar'
}
您可以使用工厂功能:

class Foo {
    @GenerateGetterAndSetter() _bar: string;
}

type FooImplementation = {
    bar(): string;
    bar(value: string): Foo;
}

function createFoo(): Foo & FooImplementation {
    return new Foo() as Foo & FooImplementation;
}

但是您将无法返回
this
,只能返回
Foo

装饰器是如何实现的?在任何情况下都不能有两个同名的方法,你知道吗?@NitzanTomer-Yes。我的decorator工作正常,它生成一个方法,根据
参数执行不同的操作。length
。好的,检查我修改的答案谢谢澄清这是不可能的。我希望在将来的版本中看到类内部的
declare
,因为我不知道它是如何有害的,但似乎很少有人在做这种事情。我不会等待
declare
被允许脱离环境上下文,因为它有一个非常特定的porpuse(参见本文:)。在您的例子中,我只是将实现分成两个不同的函数(它可能还会创建更可读的代码),然后使用mixin技巧