TypeScript singleton types All In One
单例类型 / 字面量类型
singleton types
/ literal types
-
enum member types
-
numeric literal types
-
string literal types
type EventName = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventName) {
// do something
}
handleEvent(document.getElementById('btn') as HTMLElement, 'scroll');
// ✅
handleEvent(document.getElementById('btn') as HTMLElement, 'dblclick');
// ❌ Argument of type '"dblclick"' is not assignable to parameter of type 'EventName'.(2345)