通过为参数、返回值和可选参数指定类型,让你的函数更安全。
在 Kodokon 中打开本课函数是一个可复用的小程序:它接收参数(它的输入),并可以返回一个值(它的输出)。为函数指定类型意味着指明每个参数的类型,然后是返回值的类型,写在右括号之后。
function greet(name: string): string {
return "Hello " + name + "!";
}
const message = greet("Karim");
console.log(message); // "Hello Karim!"有些函数什么都不返回:它们只是执行一个动作,比如显示一条消息。这时它们的返回类型是 void,这个词的意思是“空”。如果你试图把它们的结果当作一个值来使用,TypeScript 会向你发出警告。
function logWelcome(name: string): void {
console.log("Welcome, " + name + "!");
}
logWelcome("Fatou"); // prints, but returns nothing就像接口的属性一样,参数也可以用 ? 变为可选。这样调用者可以提供它,也可以不提供。在函数内部,记得处理它缺失的情况。
function makeCoffee(size: string, sugar?: boolean) {
if (sugar) {
return "A " + size + " coffee with sugar.";
}
return "A " + size + " coffee without sugar.";
}
makeCoffee("large", true); // with sugar
makeCoffee("small"); // sugar is missingfunction repeat(word: string, times: number = 2) {
return word.repeat(times);
}
console.log(repeat("ha")); // "haha"
console.log(repeat("ha", 3)); // "hahaha"