//联合类型
let list: (string|number)[] = ['Xcat Liu', 25];
let arrr: Array<string|number> = ['Xcat Liu', 25];
//类
class Animal {
public age: string;//成员01,public可省略,默认是public
public constructor(message: string) { //成员02
this.age = message;
}
public greet() { //成员03
return 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 error
return arg;
}
loggingIdentity('string');
//泛型接口,支持设置具体类型
interface setType<T>{
(arg:T):T;
}
//identity 可以随意入参,但是入什么类型,一定返回什么类型
function identity<T>(arg: T): T {
return arg;
}
//myIdentity 强制string格式的入参,返回也是string
let 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"); // okay
getProperty(x, "m"); //报错,因为x.m = undefined;
//private
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // 错误: 'name' 是私有的.