目前,TypeScript不允许在接口中使用get/set方法(访问器).

interface I {
      get name():string;
}

class C implements I {
      get name():string {
          return null;
      } 
}

此外,TypeScript不允许在类方法中使用数组函数表达式:

class C {
    private _name:string;

    get name():string => this._name;
}

有没有其他方法可以在接口定义上使用getter和setter?

推荐答案

可以在接口上指定属性,但不能强制使用getter和setter,如下所示:

interface IExample {
    Name: string;
}

class Example implements IExample {
    private _name: string = "Bob";

    public get Name() {
        return this._name;
    }

    public set Name(value) {
        this._name = value;
    }
}

var example = new Example();
alert(example.Name);

在本例中,接口不强制类使用getter和setter,我本可以使用一个属性(下面的示例)——但接口应该隐藏这些实现细节,因为它向调用代码promise 可以调用什么.

interface IExample {
    Name: string;
}

class Example implements IExample {
    // this satisfies the interface just the same
    public Name: string = "Bob";
}

var example = new Example();
alert(example.Name);

最后,=>是不允许用于类方法的——如果你认为它有一个火爆的用例,你可以使用start a discussion on Codeplex.下面是一个例子:

class Test {
    // Yes
    getName = () => 'Steve';

    // No
    getName() => 'Steve';

    // No
    get name() => 'Steve';
}

Typescript相关问答推荐

使用新控制流的FormArray内部的Angular FormGroup

如何使用另一个类型的属性中的类型

类型安全JSON解析

基于键的值的打字动态类型;种类;

我可以为情态车使用棱角形的路由守卫吗?

如何在编译时为不带常量的参数引发错误

为什么我的条件类型不能像我预期的那样工作?

如何在Typescript 中组合unions ?

APP_INITIALIZER在继续到其他Provider 之前未解析promise

在类型脚本中将泛型字符串数组转换为字符串字母并集

将带有样式的Reaction组件导入到Pages文件夹时不起作用

如何从上传文件中删除预览文件图标?

如何为带有参数的函数类型指定类型保护?

如何创建一个将嵌套类属性的点表示法生成为字符串文字的类型?

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

两个名称不同的相同打字界面-如何使其干燥/避免重复?

如何使用angular15取消选中位于其他组件中的复选框

我如何键入它,以便具有字符串或数字构造函数的数组可以作为字符串或数字键入s或n

记录的子类型<;字符串,X>;没有索引签名

如何使用 AWS CDK 扩展默认 ALB 控制器策略?