天天看點

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,
  };
}
      

繼續閱讀