typescript:第二章_变量声明

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录 前一修订版
typescript:第二章_变量声明 [2026/03/09 15:49] – [2.5.3 函数参数解构] 张叶安typescript:第二章_变量声明 [2026/06/08 10:53] (当前版本) – [2.5.3 函数参数解构] 张叶安
行 332: 行 332:
  
 ==== 2.5.3 函数参数解构 ==== ==== 2.5.3 函数参数解构 ====
-函数中写解构的就不需要=号+=== 1. 基本概念 === 
 +函数参数解构是:函数接收一个对象或数组作为参数时直接在参数列表中把需要的值取出来。
  
-<code> +普通写法通常是先接收整个对象,再从对象中取属性: 
-export default function AppGroupLayout({children,}: Readonly<{ children: React.ReactNode }>) + 
-{+<code typescript
 +type Props = Readonly<{ children: React.ReactNode }>; 
 + 
 +export default function AppGroupLayout(props: Props) { 
 +  const children = props.children;
   return <AppLayout>{children}</AppLayout>;   return <AppLayout>{children}</AppLayout>;
 } }
 </code> </code>
  
-函数接收一个对象参数,这个对象里有 children 属性;通过对象解构把 children 直接取出来,并给整个参数对象加上 TypeScript 类型+使用函数参数解构后,可以在参数位置直接取出 ''children''
  
-这里"{children,}: Readonly<{ children: React.ReactNode }>"作用类似于"Readonly<{children:React.ReactNode}>" +<code typescript> 
- +export default function AppGroupLayout( 
-解构内容是把输入参数的 children属性取出来供后续使用 +  { children }: Readonly<{ children: React.ReactNode }> 
- +) { 
- +  return <AppLayout>{children}</AppLayout>;
-<code> +
-// 对象参数解构 +
-function greetUser({ name, age }: { name: string; age: number }): string +
-  return `Hello ${name}, you are ${age} years old`;+
 } }
 +</code>
  
-// 带默认值 +这里的含义是:
-function createUser({  +
-  name,  +
-  age = 18,  +
-  role = "user"  +
-}: {  +
-  name: string;  +
-  age?: number;  +
-  role?: string; +
-}) { +
-  return { name, age, role }; +
-+
- +
-// 数组参数解构 +
-function processCoordinates([x, y]: [number, number]): string { +
-  return `X: ${x}, Y: ${y}`; +
-+
- +
-// 嵌套解构 +
-function processUser({  +
-  name,  +
-  address: { city, country }  +
-}: {  +
-  name: string;  +
-  address: { city: string; country: string }; +
-}) { +
-  return `${name} lives in ${city}, ${country}`; +
-+
-</code>+
  
 +  * 函数接收一个对象参数。
 +  * 这个对象里有一个 ''children'' 属性。
 +  * ''{ children }'' 表示从参数对象中取出 ''children''
 +  * '': Readonly<{ children: React.ReactNode }>'' 表示给整个参数对象添加 TypeScript 类型。
 +  * 函数体里可以直接使用 ''children'',不需要再写 ''props.children''
 ==== 2.5.4 解构与类型注解 ==== ==== 2.5.4 解构与类型注解 ====
  

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • typescript/第二章_变量声明.1773042559.txt.gz
  • 最后更改: 2026/03/09 15:49
  • 张叶安