函数返回值
// 定义函数返回值
function greet():string { // 返回一个字符串
return "Hello World"
}
函数参数
function add(x: number, y: number): number {
return x + y;
}
console.log(add(1,2))
参数是一个json对象:
public async Login(userInfo: { userAccount:string, password:string, identification:string, rememberMe:string}) {
let { userAccount, password,identification,rememberMe } = userInfo
userAccount = userAccount.trim()
await login({ userAccount, password,identification,rememberMe })
setToken("LOGIN")
this.SET_TOKEN("LOGIN")
}
可选参数/默认参数/剩余参数
在 TypeScript 函数里,如果我们定义了参数,则我们必须传入这些参数,除非将这些参数设置为可选,可选参数使用问号标识 ?
function buildName(firstName: string, lastName: string) {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // 错误,缺少参数
let result2 = buildName("Bob", "Adams", "Sr."); // 错误,参数太多了
let result3 = buildName("Bob", "Adams"); // 正确
- 可选参数使用问号标识?
```typescript
//可选参数使用问号标识?
function buildName(firstName: string, lastName?: string) {
if (lastName)
elsereturn firstName + " " + lastName;
}return firstName;
let result1 = buildName(“Bob”); // 正确 let result2 = buildName(“Bob”, “Adams”, “Sr.”); // 错误,参数太多了 let result3 = buildName(“Bob”, “Adams”); // 正确
- 默认参数
```typescript
function calculate_discount(price:number,rate:number = 0.50) {
var discount = price * rate;
console.log("计算结果: ",discount);
}
calculate_discount(1000) // 正确
calculate_discount(1000,0.30)// 正确
- 剩余参数:当我们不知道要向函数传入多少个参数,这时候我们就可以使用剩余参数来定义 ```typescript function buildName(firstName: string, …restOfName: string[]) { return firstName + “ “ + restOfName.join(“ “); }
let employeeName = buildName(“Joseph”, “Samuel”, “Lucas”, “MacKinzie”); ```