Object Properties
TypeScript ⟩
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
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
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
Was this helpful?