Object Properties

Optional

// 
interface PaintOptions {
  x?: number;              // ⭐️ optional
  y?: number;
}

/*
interface Shape {
  paint(opts: PaintOptions = {});
}
*/

const shape = getShape();

shape.paint({ });
shape.paint({ x: 100 });
shape.paint({ y: 100 });
shape.paint({ x: 100, y: 100 });

readonly

readonlyconst 的作用差不多,會保護 Primitives 不受更改,但對於 Object 來說,雖然不能更改物件本身,但可更改屬性

interface SomeType {
  readonly prop: string;      // ⭐️ readonly
}
interface Person {
  name: string;
  age : number;
}
 
interface ReadOnlyPerson {
  readonly name: string;      // ⭐️ readonly
  readonly age : number;      // ⭐️ readonly
}

// writable
let person: Person = {
  name: "Person McPersonface",
  age: 42,
};
 
// ⭐️ point to same person
let readonlyPerson: ReadOnlyPerson = person;
 
readonlyPerson.age;              // prints '42'
person.age++;                    // person is writable ⭐️
readonlyPerson.age;              // prints '43'

Index Signatures

TypeScript 的 index signature 類似於 Swift 的 subscript

interface StringArray {
//╭─── ⭐️ ───╮
  [ index: T ]: string;       // ⭐️ index signature
}                             //    T = string or number
 
const a: StringArray = getStringArray();
const item = a[0];

Last updated

Was this helpful?