每个函数都有一个函数名、主体和返回值。
返回值是任何类型的值,而javascript不声明返回类型。
在typescript中,每个函数都返回数据。
typescript是否允许声明返回类型?
为一个函数声明返回类型并不是强制性的。
下面是一个函数返回类型的语法
函数返回类型的声明是在函数后面加上冒号的类型。
functionName() : returntype { ... }
例如,在下面的例子中,声明一个带有welcome()方法的类,返回类型没有用类型声明。
Typescript编译器从返回值中推断出类型,并假定该函数返回的是字符串。
尽管它是有效的并且在typescript中执行得很好。
class HelloWorld {
welcome() {
return "Hello World Example "; // type infered to be string
}
}
下面是一个用Boolean 类型声明函数的例子。
class Utils {
IsNull(str:string):boolean {
if(str){
return true;
}
return false;
}
}
推荐的方法是用有效的返回类型来声明一个函数。
class HelloWorld {
welcome() :string {
return "Hello World Example "; // type infered to be string
}
}
函数返回多种数据类型
typescript中的函数可以使用union类型返回多种类型。
语法
functionName() : returntype1|returntype2 { ... }
让我们写一个字符串等值的例子
function isEqual(str1: string, str2: string): boolean| string {
return str1 == str2 ? true : 'Not Equal';
}
在上面的例子中,该函数检查字符串是否相等,并返回boolean 或string 。
同样地,使用type关键字语法创建新类型
type StringAndBoolean=boolean| string;
function isEqual(str1: string, str2: string): StringAndBoolean {
return str1 == str2 ? true : 'Not Equal';
}
声明返回无效的函数类型
一个返回另一个函数的函数。而且,函数也可以用void返回类型来返回函数。
使用()=>void来返回函数void的返回类型
parentFunction(): () => void {
return () => {
console.log('Parent function print');
};
}
匿名函数返回类型声明
匿名函数是没有函数名的函数。它使用箭头函数(=>)。
在冒号(:)符号后声明类型。下面是一个匿名函数,它返回的是string 类型。
const getMessage = (): string => "hello test";
返回类型void的例子
const printLog = (): void => console.log("hello test");
函数声明从一个函数返回的对象
接口或类的类型脚本中的对象。
让我们用接口来声明一个对象
interface Employee {
id: number;
name: string;
}
下面的函数返回一个多属性的对象 对象返回类型在冒号后声明对象的类型。
function insertEmployee(id: number,name: string) : Employee {
// db operation
return {
id: 1,
name: "john"
};
};