Object types
k items vs n items
in the following paragraphs:
- items refer to the members of an object, aka the key-value pairs.
- object with k items refers to a fixed amount of items: the number of items is controlled by TypeScript.
- object with n items refers to any number of items: the number of items is not controlled by TypeScript.
arrays
n elements of the same type:
let a: T[]
let a: number[] // an array of number elements
// Array<number>
// 2D array
let a: number[][] // an array or array of number elements
note: technically, JavaScript supports arrays with elements of different type, but it's best not to use them.
tuples
an array of k elements, each with a specific type:
let t: [T, U]
let t: [x: T, y: U]
let t: [number, string]
let t: [hp: number, name: string] // labels purely for documentation
plain objects with k items (records)
a plain object with k items, aka a fixed list of properties, each with a name and a type.
interface PlayableCharacter {
id: string
level: number
}
type PlayableCharacter = {
id: string
level: number
}
plain objects with n items, with values of the same type (dictionaries)
n items of the same kind:
// Record<string, Word>
type WordDic = {
[key: string]: Word
}
This fits dictionaries with any number of items.
plain objects with k items, with values of the same type (dictionaries)
The object has exactly k items, as the keys are constrained to a type union:
// Record<StructureName, Structure>
type PlanetStructures = {
[key in StructureName]: Structure
}
This fits object that must provide an item for each value in a type union.
plain objects with k or less items, with values of the same type (dictionaries)
The object has k or less items, with keys conforming to a type union, with no exhaustivity:
type PlanetStructures = {
[key in StructureName]?: Structure
}
the convention of using key
The term key in [key: string] or [key in ..] is a convention: we can use any other term, as it is for syntax only.