type Name = string; type NameResolver = () =>string; type NameOrResolver = Name | NameResolver; functiongetName(n: NameOrResolver): Name{ if (typeof n === 'string') { return n; } else { return n(); } }
字符串字面量类型
字符串字面量类型用来约束取值只能是某几个字符串中的一个
1 2 3 4 5 6 7
type EventNames = 'click' | 'scroll' | 'mousemove'; functionhandleEvent(ele: Element, event: EventNames) { // do something } handleEvent(document.getElementById('hello'), 'scroll'); // 没问题 handleEvent(document.getElementById('world'), 'dbclick'); // 报错,event 不能为 'dbclick' // index.ts(7,47): error TS2345: Argument of type '"dbclick"' is not assignable to parameter of type 'EventNames'.
let tom: [string, number]; tom[0] = 'Tom'; tom[1] = 25;
tom[0].slice(1); tom[1].toFixed(2);
let tom: [string, number]; tom[0] = 'Tom';
let tom: [string, number]; tom = ['Tom', 25];
let tom: [string, number]; tom = ['Tom']; // Property '1' is missing in type '[string]' but required in type '[string, number]'.
let tom: [string, number]; tom = ['Tom', 25]; tom.push('male'); tom.push(true); // Argument of type 'true' is not assignable to parameter of type 'string | number'.
let a = new Animal('Jack'); console.log(a.name); // Jack a.name = 'Tom';
// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'. // index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.