1.函数类型:
三种定义函数的方式:
function func(name: string, age: number): string {
return name + ' is ' + age;
}
let funcA = function(name: string, age: number): string {
return name + ' is ' + age;
}
let funcB: (name: string, age: number) => string = function(n: string, age: number) {
return n + ' is ' + age;
}
2.类型推导:赋值语句一边指定返回值类型,另一边未指定,ts编译器会自动识别出类型。
let funcD: (x: number, y: number) => number = function(x, y) {
return x + y;
}
let funcD: (x: number, y: number) => number = function(x, y) {
return x + y + 'a'; // 不指定返回值类型时,编辑器没有提示,但编译时会报错
}
3.可选参数(?)和默认参数:默认每个参数是必传的。可选参数必须放到参数列表最后;默认参数位置随意,但默认参数出现在必须参数前边,默认参数必须传值(可为undefined)
// 可选参数
function buildName(name: string, age?: number): string {
if (age) {
return 'name: ' + name;
} else {
return 'name: ' + name + ' age: ' + age;
}
}
buildName('ltt');
buildName('ltt', 20);
buildName('ltt', 20, 'nv'); // error: Expected 1-2 arguments, but got 3.
默认参数:必须参数后加默认值后变为可选
function buildName(age = 20, name: string) {
return 'name: ' + name + ' age: ' + age;
}
buildName(undefined ,'ltt');
buildName(18, 'ltt');
4.剩余参数:用...加变量名来表示剩余参数
function restFunc(first: string, ...rest: string[]): string {
return first + rest.join(' ');
}
restFunc('ltt', 'Jsb', 'Meili');
5.this:ts中的this与js是相同的:在函数被调用时,才能确定this的指向,指向调用它的对象;在箭头中,this保存的是函数被创建时的指向,而不是调用时的值。
interface PigSettings {
age: number;
sex: string;
}
interface Animal {
age: number;
sex: string;
createAnimal(this: Animal): () => PigSettings;
}
let Pig: Animal = {
age: 18,
sex: 'nv',
createAnimal() {
return function() {
return {age: this.age, sex: this.sex};
}
}
}
let createAnimal = Pig.createAnimal();
console.log(createAnimal()); // { age: undefined, sex: undefined }
此时,是拿不到this.age和this.sex,因为函数调用时this指向window。将Pig对象做如下改造即可:
let Pig: Animal = {
age: 18,
sex: 'nv',
createAnimal() {
return () => {
return {age: this.age, sex: this.sex};
}
}
}
this作为参数时,需注意this的类型:
不同文件中有相同的接口实例名时会做检测。








网友评论