🏷️ TypeScript - Object Types
You can define object types as type aliases or with the interface keyword. Most projects prefer the interface-style.
They mostly behave the same, but
interfacehas a few advantages:
- Interfaces can be merged, while type aliases can't.
- Interfaces can be implemented by classes, while type aliases can't.
- Interfaces are marginally more performant.
- Interfaces can generate better error messages in edge cases.
type User = {
name: string;
age: number;
};
interface User {
name: string;
age: number;
}
Move nested object types under their own names. It makes both the code and error messages more readable.
interface Address {
street: string;
city: string;
}
interface User {
name: string;
age: number;
address: Address
}
A property declared as optional with ? is allowed to not exist. A property declared as | undefined must still exist, even if the value is undefined.
interface User {
name: string;
age: number;
address?: Address;
phone: string | undefined;
}
Object properties support readonly prefix. This tells TypeScript that the property shouldn't be changed after it has been set.
TypeScript is structurally typed, not duck typed. Excess property checks will trigger anywhere a new object of that type is being created. Like array members, class fields, and function parameters.
Object functions can be methods or properties.
You'd normally only use the
methodstyle if the interface will be used to declare how classes look.
interface HasBothFunctionTypes {
property: () => string;
method(): string;
}
const hasBoth: HasBothFunctionTypes = {
property: () => "",
method() {
return "";
}
};
hasBoth.property();
hasBoth.method();
Sources
- Learning TypeScript by Josh Goldberg