差别
这里会显示出您选择的修订版和当前版本之间的差别。
| 后一修订版 | 前一修订版 | ||
| typescript:第二章_变量声明 [2026/03/09 15:22] – 创建 张叶安 | typescript:第二章_变量声明 [2026/06/08 10:53] (当前版本) – [2.5.3 函数参数解构] 张叶安 | ||
|---|---|---|---|
| 行 289: | 行 289: | ||
| ==== 2.5.2 对象解构 ==== | ==== 2.5.2 对象解构 ==== | ||
| + | |||
| + | 对象解构的意思就是从等式右边取出变量的值并供后续使用。 | ||
| + | |||
| < | < | ||
| 行 298: | 行 301: | ||
| }; | }; | ||
| - | const { name, age, email } = user; | + | const { name, age, email } = user;// |
| console.log(name); | console.log(name); | ||
| // 重命名 | // 重命名 | ||
| - | const { name: userName, age: userAge } = user; | + | const { name: userName, age: userAge } = user; 从user中取出参数并重命名供后面使用 |
| console.log(userName); | console.log(userName); | ||
| 行 326: | 行 329: | ||
| console.log(rest); | console.log(rest); | ||
| </ | </ | ||
| + | |||
| ==== 2.5.3 函数参数解构 ==== | ==== 2.5.3 函数参数解构 ==== | ||
| + | === 1. 基本概念 === | ||
| + | 函数参数解构指的是:函数接收一个对象或数组作为参数时,直接在参数列表中把需要的值取出来。 | ||
| - | < | + | 普通写法通常是先接收整个对象,再从对象中取属性: |
| - | // 对象参数解构 | + | |
| - | function greetUser({ name, age }: { name: string; age: number }): string { | + | |
| - | return `Hello ${name}, you are ${age} years old`; | + | |
| - | } | + | |
| - | // 带默认值 | + | <code typescript> |
| - | function createUser({ | + | type Props = Readonly< |
| - | name, | + | |
| - | age = 18, | + | |
| - | role = " | + | |
| - | }: { | + | |
| - | name: string; | + | |
| - | age?: number; | + | |
| - | role?: string; | + | |
| - | }) { | + | |
| - | return { name, age, role }; | + | |
| - | } | + | |
| - | // 数组参数解构 | + | export default |
| - | function | + | const children = props.children; |
| - | return | + | return |
| } | } | ||
| + | </ | ||
| - | // 嵌套解构 | + | 使用函数参数解构后,可以在参数位置直接取出 '' |
| - | function | + | |
| - | | + | <code typescript> |
| - | address: | + | export default |
| - | }: { | + | { children |
| - | name: string; | + | ) { |
| - | address: { city: string; country: string | + | return |
| - | }) { | + | |
| - | return | + | |
| } | } | ||
| </ | </ | ||
| + | 这里的含义是: | ||
| + | |||
| + | * 函数接收一个对象参数。 | ||
| + | * 这个对象里有一个 '' | ||
| + | * '' | ||
| + | * '': | ||
| + | * 函数体里可以直接使用 '' | ||
| ==== 2.5.4 解构与类型注解 ==== | ==== 2.5.4 解构与类型注解 ==== | ||