//联合类型

    1. let list: (string|number)[] = ['Xcat Liu', 25];
    2. let arrr: Array<string|number> = ['Xcat Liu', 25];

    //类

    1. class Animal {
    2. public age: string;//成员01,public可省略,默认是public
    3. public constructor(message: string) { //成员02
    4. this.age = message;
    5. }
    6. public greet() { //成员03
    7. return this.age;
    8. }
    9. }
    10. class Cat extends Animal {
    11. constructor(age: string) { super(age); }
    12. greet() {
    13. return text || '嘿嘿嘿!'
    14. }
    15. }
    16. const tuy = new Cat('你妹');
    17. console.log(tuy.greet());

    //泛型

    1. //最基本的泛型
    2. function base<T>(arg:T):T{
    3. return arg;
    4. }
    5. //泛型接口约束,强制需要length属性才行
    6. interface hasLength {
    7. length: number;
    8. }
    9. function loggingIdentity<K extends hasLength>(arg: K): K {
    10. console.log(arg.length); // Now we know it has a .length property, so no more error
    11. return arg;
    12. }
    13. loggingIdentity('string');
    14. //泛型接口,支持设置具体类型
    15. interface setType<T>{
    16. (arg:T):T;
    17. }
    18. //identity 可以随意入参,但是入什么类型,一定返回什么类型
    19. function identity<T>(arg: T): T {
    20. return arg;
    21. }
    22. //myIdentity 强制string格式的入参,返回也是string
    23. let myIdentity: setType<string> = identity;//强制指定只能输入数字
    24. myIdentity('123')
    25. //key必须是Object.keys(obj)的成员,否则报错
    26. function getProperty<T, K extends keyof T>(obj: T, key: K) {
    27. return obj[key];
    28. }
    29. let x = { a: 1, b: 2, c: 3, d: 4 };
    30. getProperty(x, "a"); // okay
    31. getProperty(x, "m"); //报错,因为x.m = undefined;

    //private

    1. class Animal {
    2. private name: string;
    3. constructor(theName: string) { this.name = theName; }
    4. }
    5. new Animal("Cat").name; // 错误: 'name' 是私有的.