typescript - TypeScript:销毁参数时如何指定函数参数的类型?
问题描述
TS 因错误而炸毁:
错误:(8, 20) TS7031:绑定元素“on”隐含地具有“any”类型。
错误:(8, 24) TS7031:绑定元素 'children' 隐含地具有 'any' 类型。
我有以下功能。我传递了两个论点。
//
function On({on, children}) {
return (
<div>{on} {children}</div>
)
}
在这种情况下如何指定参数的类型?此语法不起作用:
function On({(on as boolean), (children as HTMLElement[])}) {
function On({(on: boolean), (children: HTMLElement[])}) {
function On({on: boolean, children: HTMLElement[]}) {
return (
<div>{on} {children}</div>
)
}
解决方案
像这样:
function On({on, children} : {on: boolean, children: HTMLElement[] }) {
// your code
}
如果您有整个对象的类型/接口,您还可以使用它来使您的代码更具可读性:
interface OnOptions {
on: boolean;
children: HTMLElement[];
someOtherProp: string;
}
function On({on, children} : OnOptions) {
// your code
}
推荐阅读
- php - 在 PhpStorm 中启用 Xdebug
- javascript - 如何从我的反应应用程序中删除所有会话 cookie?
- sql - 如何更新参考预言机
- sql - SQL FOR JSON:为每个对象创建行
- unity3d - 饱和度渐变 - 后处理
- amazon-web-services - 即使存在信任关系,也无法在 AWS CLI 中担任角色
- typescript - 迁移失败:发现不兼容的对等依赖项
- python - Pandas 用该列的滚动总和替换列值
- node.js - Mongoose:“模式”类型上不存在属性“方法”。您指的是 “method” 吗?
- c# - Oracle Cloud Logging 使用 OCI .Net SDK 提取日志。错误:“无法处理 JSON 输入”