//联合类型
let list: (string|number)[] = ['Xcat Liu', 25];let arrr: Array<string|number> = ['Xcat Liu', 25];
//类
class Animal {public age: string;//成员01,public可省略,默认是publicpublic constructor(message: string) { //成员02this.age = message;}public greet() { //成员03return this.age;}}class Cat extends Animal {constructor(age: string) { super(age); }greet() {return text || '嘿嘿嘿!'}}const tuy = new Cat('你妹');console.log(tuy.greet());
//泛型
//最基本的泛型function base<T>(arg:T):T{return arg;}//泛型接口约束,强制需要length属性才行interface hasLength {length: number;}function loggingIdentity<K extends hasLength>(arg: K): K {console.log(arg.length); // Now we know it has a .length property, so no more errorreturn arg;}loggingIdentity('string');//泛型接口,支持设置具体类型interface setType<T>{(arg:T):T;}//identity 可以随意入参,但是入什么类型,一定返回什么类型function identity<T>(arg: T): T {return arg;}//myIdentity 强制string格式的入参,返回也是stringlet myIdentity: setType<string> = identity;//强制指定只能输入数字myIdentity('123')//key必须是Object.keys(obj)的成员,否则报错function getProperty<T, K extends keyof T>(obj: T, key: K) {return obj[key];}let x = { a: 1, b: 2, c: 3, d: 4 };getProperty(x, "a"); // okaygetProperty(x, "m"); //报错,因为x.m = undefined;
//private
class Animal {private name: string;constructor(theName: string) { this.name = theName; }}new Animal("Cat").name; // 错误: 'name' 是私有的.
