簡體   English   中英

打字稿抱怨沒有分配get屬性

[英]Typescript complaining about not assigning a get property

我有這個代碼stackblitz

export class Student {
  id: number;
  name: string;
  age?:number;

  get studentType():string {
    return 'fullTime'
  }

  constructor(params: Student) {
    Object.assign(this, params);
  }
}

const student = new Student({id:1, name: 'Jon'}); //ts error here

我收到以下錯誤

類型'{{id:number; 名稱:字符串; }”不能分配給“學生”類型的參數。 類型'{id:number;缺少屬性'studentType'。 名稱:字符串; }”。

雖然studentType是僅獲取屬性,無法下注設置。

原因是什么,我該如何解決?

PS。 (我不想像studentType?那樣使它為可空值或將其轉換為一個函數)

Getters / Setters與常規屬性完全一樣,這就是為什么Typescript不能區分getter / setter和常規屬性。 您可以將所有屬性設置為可選,從而可以省略studentType

  constructor(params: Partial<Student>) {
     Object.assign(this, params);
  }

但是,其他屬性(例如name )現在也可以省略。 為了提高類型安全性,您可以引入其他接口:

export interface StudentData {
  id: number;
  name: string;
  age?:number;
}

export class Student implements StudentData {
  get studentType():string {
    return 'fullTime'
  }

  constructor(params: StudentData) {
     Object.assign(this, params);
   }
 }

在TypeScript中,這是一個更具爭議性的話題。 對於類,TypeScript將類的整體形狀視為類型。

這包括私有變量和方法,在這種情況下,包括getter / setter。

解決問題的一種方法是可以使用Partial<>

constructor(params: Partial<Student>) { ... }

Pick<>

constructor(params: Pick<Student, 'id' | 'name' | 'age'>) { ... }

另一種方法是自己創建一個接口:

interface IStudent { id: number, name: string, age?:number }
class Student implements IStudent {
  constructor(params: IStudent) { ... }
}

是什么原因呢?

基本上, {id:1, name: 'Jon'}不是學生,因為該對象缺少studentType屬性。 這似乎很明顯而且很愚蠢,但是很有意義,因為打字稿無法知道您是否要依賴該參數的屬性。

在構造函數中,只需調用Object.assign並放手即可。 但是您可能正在調用實際上依賴於具有該屬性的參數的某些函數,如果打字稿未指出,則可能導致運行時錯誤。

以及我該如何解決?

好吧,已經有幾個答案了。 我只需要正確輸入構造函數參數即可。 如果您希望對象具有ID,名稱和/或年齡,則可以相應地輸入:


export class Student {
  id: number;
  name: string;
  age?:number;

  get studentType():string {
    return 'fullTime'
  }

  constructor(params: {id: number, name: string, age?: number}) {
    Object.assign(this, params);
  }
}

const student = new Student({id:1, name: 'Jon'}); //ts error here

這是因為您將構造函數中的類型指定為Student。 可以這樣做:

export class Student {
  id: number;
  name: string;
  age?: number;

constructor(id:number, name:string,age?:number) {
    this.age = age;
    this.name = name;
    this.id = id;
}

  get studentType():string {
    return 'fullTime'
  }

}

const student = new Student(1, 'Jon');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM