官术网_书友最值得收藏!

Type inference

Type inference is used when the type is not provided explicitly. For instance in the following statements:

var x = "hello";
var y = 99;

These don't have explicit type annotations. TypeScript can infer that x is a string and y is a number. As you see, the type can be omitted if the compiler is able to infer it. TypeScript improves the type inference continuously. It tries to guess a best common type when elements of several types are present in an array. The type of the following variable animal, where Sheepdog extends Dog, is Dog[]:

let animal = [new Dog(), new Sheepdog()];

The best common type of the next array is (Dog | Fish)[] because the class Fish doesn't extend to any other class:

class Fish {
kind: string;
}

let animal = [new Dog(), new Sheepdog(), new Fish()];

Type inference is also used for functions. In the next example, the compiler can figure out the types of the function's parameter (string) and the return value (boolean):

let isEmpty: (param: string) => boolean;
isEmpty = function(x) {return x === null || x.length === 0};
主站蜘蛛池模板: 古浪县| 石屏县| 西贡区| 电白县| 百色市| 桐乡市| 华蓥市| 北宁市| 涿州市| 阿拉尔市| 聊城市| 读书| 汉源县| 开化县| 虎林市| 巧家县| 炉霍县| 柘城县| 江陵县| 华容县| 梁河县| 张北县| 汾西县| 安吉县| 寻乌县| 房产| 沙雅县| 敖汉旗| 类乌齐县| 承德县| 绥芬河市| 祁东县| 渭南市| 乐业县| 鄂州市| 云和县| 阿合奇县| 曲靖市| 成武县| 策勒县| 衡水市|