type Name = string; type NameResolver = () => string; type NameOrResolver = Name | NameResolver; functiongetName(n: NameOrResolver): Name { if (typeof n === 'string') { return n; } else { returnn(); } }
字符串字面量类型
字符串字面量类型用来约束取值只能是某几个字符串中的一个
1 2 3 4 5 6 7 8 9
type EventNames = 'click' | 'scroll' | 'mousemove'; functionhandleEvent(ele: Element, event: EventNames) { // do something }