TypeScript Objects¶
const activeGlobalFilters = typeToFilter[
globalFilter
] as typeof filterOptions[keyof typeof filterOptions];
Object that has at least these two properties¶
Extend a type¶
interface LoadingWidgets {
[widgetId?: number]: boolean;
}
interface IsLoading {
widgets: LoadingWidgets;
[key?: string]: boolean | LoadingWidgets;
}
Avoid optional properties¶
- Explicitly model which combinations exist and which don't
interface Product {
id: string;
type: "digital" | "physical";
weightInKg?: number;
sizeInMb?: number;
}
interface Product {
id: string;
type: "digital" | "physical";
}
interface DigitalProduct extends Product {
type: "digital";
sizeInMb: number;
}
interface PhysicalProduct extends Product {
type: "physical";
weightInKg: number;
}
Record¶
Restrict what the key and the value can be
- restrict the keys (string
union)
- restrict the values
type User = {
name: string;
email: string;
};
type Country = "uk" | "france" | "india";
const myData: Record<Country, User> = {
uk: { name: "John", email: "a@a.a" },
france: { name: "Sarah", email: "a@a.a" },
india: { name: "Jane", email: "a@a.a" },
};
Empty object¶
Record: object of string -> string¶
object
type vs UnknownObject
¶
object
will match functions too!
Narrowing which props are accepted for subtypes
There is something
Enums¶
- enums have issues
- union of strings
type Options = 'one' | 'two' | 'three'
- https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#enum-types
May be fixed in TypeScript 5.0?
How to iterate over string union¶
const names = ["Bill Gates", "Steve Jobs", "Linus Torvalds"] as const;
type Names = typeof names[number];
Last update:
2023-04-24