天天看點

TypeScript 的 Object Types

有三種方式定義 TypeScript 的 object Types.

1. 匿名類型 - anonymous type

function greet(person: { name: string; age: number }) {
  return "Hello " + person.name;
}
           

2. 使用 interface

interface Person {
  name: string;
  age: number;
}


function greet(person: Person) {
  return "Hello " + person.name;
}
           

3. 使用 type alias

type Person = {
  name: string;
  age: number;
};


function greet(person: Person) {
  return "Hello " + person.name;
}
           

對象類型中的每個屬性都可以指定幾項内容:類型、屬性是否可選以及是否可以寫入該屬性。

read only 屬性

使用 readonly 修飾符并不一定意味着一個值是完全不可變的——或者換句話說,被 readonly 修飾的屬性,并不意味着它的内部内容不能改變。 這隻是意味着屬性本身不能被重寫。

interface Home {
  readonly resident: { name: string; age: number };
}


function visitForBirthday(home: Home) {
  // We can read and update properties from 'home.resident'.
  console.log(`Happy birthday ${home.resident.name}!`);
  home.resident.age++;
}


function evict(home: Home) {
  // But we can't write to the 'resident' property itself on a 'Home'.
  home.resident = {
Cannot assign to 'resident' because it is a read-only property.Cannot assign to 'resident' because it is a read-only property.
    name: "Victor the Evictor",
    age: 42,
  };
}
           

Index Signatures - 索引簽名

有時您事先并不知道類型屬性的所有名稱,但您确實知道值的形狀。

在這些情況下,您可以使用索引簽名來描述可能值的類型,例如:

interface StringArray {
  [index: number]: string;
}


const myArray: StringArray = getStringArray();
const secondItem = myArray[1];
           

StringArray 的含義是,我們有一個 StringArray 接口,它有一個索引簽名。 此索引簽名指出,當 StringArray 用數字索引時,它将傳回一個字元串。

Whenever we write out types like number[] or string[], that’s really just a shorthand for Array<number> and Array<string>.
           

number[] 和 string[] 是 Array<number> 和 Array<string> 的簡寫。

Turple - 元組

元組類型是另一種數組類型,它确切地知道它包含多少個元素,以及它在特定位置包含哪些類型。

這裡,StringNumberPair 是字元串和數字的元組類型。 與 ReadonlyArray 一樣,它在運作時沒有表示,但對 TypeScript 很重要。 對于類型系統,StringNumberPair 描述了數組,其 0 索引包含一個字元串,其 1 索引包含一個數字。

元祖的析構

TypeScript 的 Object Types

繼續閱讀