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

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};
主站蜘蛛池模板: 会理县| 无极县| 聊城市| 县级市| 申扎县| 西昌市| 诏安县| 镇远县| 广宁县| 北安市| 鸡西市| 民县| 郸城县| 东乡族自治县| 察隅县| 中方县| 东平县| 仙桃市| 彭泽县| 沾益县| 保康县| 烟台市| 江阴市| 苍山县| 牙克石市| 定安县| 沙洋县| 普格县| 阿尔山市| 瑞丽市| 五寨县| 甘德县| 乡宁县| 泽普县| 北海市| 宝山区| 开化县| 连州市| 合阳县| 项城市| 云霄县|