首页 > 解决方案 > 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>
  )
}

标签: typescript

解决方案


像这样:

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
}

推荐阅读