ts 类型

作者: Jalon | 来源:发表于2016-03-29 13:34 被阅读0次

    any表示任意类型
    void则可以看作与any相反,意思是没有类型,通常一个函数如果没有返回值,那么就可以把他的返回类型设置为void。

    protected componentWillUnmount():void {
    
    }
    

    在TypeScript里,每个成员默认为public的。
    那么他的实例和继承他的类的实例是可以调用这些方法或变量的。

    当成员被标记成private时,它就不能在声明它的类的外部访问。比如:

    class Animal { 
      private name: string; 
      constructor(theName: string) { 
        this.name = theName; 
      }
    }
    new Animal("Cat").name; // Error: 'name' is private;
    

    protected
    修饰符与private
    修饰符的行为很相似,但有一点不同,protected
    成员在派生类中仍然可以访问,就是说,他的实例不可以访问这些变量或方法,但是他的子类的实例可以。


    有时候我们希望用户可以输入任何类型的值的同时,又希望返回的类型能够确定,那么就用到泛型了。

    function identity<T>(arg: T): T { 
      return arg;
    }
    

    泛型类
    泛型类看上去与泛型接口差不多。 泛型类使用(<>
    )括起泛型类型,跟在类名后面。

    class GenericNumber<T> {
        zeroValue: T;
        add: (x: T, y: T) => T;
    }
    let myGenericNumber = new GenericNumber<number>();
    myGenericNumber.zeroValue = 0;
    myGenericNumber.add = function(x, y) { return x + y; };
    

    GenericNumber类的使用是十分直观的,并且你可能已经注意到了,没有什么去限制它只能使用number类型。 也可以使用字符串或其它更复杂的类型。

    let stringNumeric = new GenericNumber<string>();
    stringNumeric.zeroValue = "";
    stringNumeric.add = function(x, y) { return x + y; };
    
    alert(stringNumeric.add(stringNumeric.zeroValue, "test"));
    

    相关文章

      网友评论

          本文标题:ts 类型

          本文链接:https://www.haomeiwen.com/subject/eqrslttx.html