Object Properties

Optional

็•ถๅฎฃๅ‘Š x?: T ๆ™‚๏ผŒx ็š„ๅž‹ๅˆฅๅฏฆ้š›ไธŠๆ˜ฏ T | undefined

// 
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

readonly ่ˆ‡ const ็š„ไฝœ็”จๅทฎไธๅคš๏ผŒๆœƒไฟ่ญท Primitives ไธๅ—ๆ›ดๆ”น๏ผŒไฝ†ๅฐๆ–ผ Object ไพ†่ชช๏ผŒ้›–็„ถไธ่ƒฝๆ›ดๆ”น็‰ฉไปถๆœฌ่บซ๏ผŒไฝ†ๅฏๆ›ดๆ”นๅ…ถๅฑฌๆ€งใ€‚

interface SomeType {
  readonly prop: string;      // โญ๏ธ readonly
}

readonly properties can be modified via aliasingโ—๏ธ

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];

An index signature property type T must be either โ€˜stringโ€™ or โ€˜numberโ€™.

It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means:

  • a[100] === a["100"]

Last updated