代码之家  ›  专栏  ›  技术社区  ›  marc_s MisterSmith

Typescript中的“Computed”属性

  •  2
  • marc_s MisterSmith  · 技术社区  · 7 年前

    伙计们,我正处于“6边学习边做”的中间。7,我多次遇到这个问题。

    假设我有一个类/接口/类型。 Person -通过Web API调用返回的一些属性-如下所示:

    export interface Person {
        FirstName: string;
        LastName: string;
        JobTitle: string;
        // so other properties - not relevant to this question
    }
    

    全名 (例如“FirstName+[Space]+LastName”),例如角网格(AG网格)或其他地方-其中I 使用concat表达式或任何东西,但我需要引用类/接口/类型上的单个属性。

    在C#,我只需要创建一个属性

    string FullName { get { return $"{FirstName} {LastName}"; } }
    

    但我怎么能用打字机呢??从我阅读和研究的情况来看,这似乎是 不支持

    4 回复  |  直到 7 年前
        1
  •  27
  •   Dai    5 年前

    如果它是一个接口,那么就没有语法,因为JavaScript中的所有属性都可以有getter/setter函数,而不是公开的字段。这是一个实施问题。

    TypeScript中的BTW成员 camelCase TitleCase :

    export interface Person {
        // get + set:
        firstName: string;
        lastName : string;
        jobTitle : string;
    
        // get-only:
        readonly fullName : string;
    }
    
    class SimplePerson implements Person {
    
        public firstName: string; // value-property (“field”)
        public lastName: string;
        public jobTitle: string;
    
        get fullName(): string { // read-only property with getter function (this is not the same thing as a “function-property”)
            return this.firstName + " " + this.lastName;
        }
    }
    

    我注意到TypeScript的设计者选择使用关键字是令人困惑的 readonly readable fullName: string; readwrite fullName: string; -C#/.NET也有同样的问题: IReadOnlyList<T>

        2
  •  8
  •   Vivick    7 年前

    Javascript支持 get set Object.defineProperty ).

    显然在typescript中有一个方便的语法(对于类):

    class MyClass{
      firstName: string;
      lastName: string;
    
      constructor(firstName: string, lastName: string){
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      get fullName(){
        return `${this.firstName} ${this.lastName}`;
      }
    }
    

        3
  •  3
  •   SiddAjmera    7 年前

    您还可以定义 get ters和 set 在JavaScript中。

    在组件类中尝试以下操作:

    person: Person;
    ...
    // You got the person Object from your Backend API.
    ...
    // Now
    get fullName() { 
      return `${this.person.firstName} ${this.person.lastName}`; 
    }
    

    然后在模板中:

    简单使用 fullName 这样地:

    <p>{{ fullName }}</p>