Hae*_*zer 6 javascript typescript
有没有办法将数组解包为函数的参数?
例如,在 python 中,如果我有:
user = ["John", "Doe"]
def full_name(first_name, last_name):
return first_name + last_name
Run Code Online (Sandbox Code Playgroud)
然后full_name(*user)解压我的user数组并将其每个项目作为 的参数传递full_name。
在 JavaScript/TypeScript 中可以实现这样的行为吗?
你想要...spread接线员。
const user = ["John", "Doe"] as const
function fullName(firstName: string, lastName: string): string {
return firstName + lastName
}
fullName(...user)
Run Code Online (Sandbox Code Playgroud)
请注意as const.
为了使其在 Typescript 中具有类型安全性,数组需要是类型的二项元组[string, string],而不仅仅是像 那样的未知长度的数组string[]。这是因为为了保证类型安全,该数组中必须至少有 2 个字符串才能满足两个参数。as const强制打字稿将该数组视为具有已知字符串和长度的元组。
| 归档时间: |
|
| 查看次数: |
4741 次 |
| 最近记录: |