相关疑难解决方法(0)

在TypeScript中获取和设置

我正在尝试为属性创建get和set方法:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}
Run Code Online (Sandbox Code Playgroud)

设置值的关键字是什么?

typescript

568
推荐指数
7
解决办法
49万
查看次数

是否可以在接口定义中使用getter/setter?

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

interface I {
      get name():string;
}

class C implements I {
      get name():string {
          return null;
      } 
}
Run Code Online (Sandbox Code Playgroud)

此外,TypeScript不允许在类方法中使用Array Function Expression:例如:

class C {
    private _name:string;

    get name():string => this._name;
}
Run Code Online (Sandbox Code Playgroud)

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

get interface accessor set typescript

76
推荐指数
2
解决办法
6万
查看次数

没有setter的属性的TypeScript接口签名.

我们在其中一个课程中有一个典型的getter,比方说

class Employee implements IEmployee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }
}
Run Code Online (Sandbox Code Playgroud)

以及使用它的界面

interface IEmployee{
     fullName: string; 
}
Run Code Online (Sandbox Code Playgroud)

当通过此接口使用实例时,如果我们尝试分配给fullName,编译器将不会警告我们没有setter,并且JS运行时只是吞下任何赋值并且不会抛出错误.有没有办法将接口成员标记为只有getter或者只有setter?

我看过这篇文章,但它已经很老了,我想知道,如果有什么改进的话.

getter setter properties interface typescript

8
推荐指数
1
解决办法
8533
查看次数

标签 统计

typescript ×3

interface ×2

accessor ×1

get ×1

getter ×1

properties ×1

set ×1

setter ×1