gpt4 book ai didi

javascript - 将对象传递给函数时如何指定 TypeScript 类型?

转载 作者:行者123 更新时间:2023-12-04 00:49:39 25 4
gpt4 key购买 nike

我有一个函数:

export default function AppNavbar({ isEditor }) {

我想指定 isEditorboolean

我试过了:

export default function AppNavbar({ isEditor: boolean }) {

但这似乎不起作用。非常感谢任何帮助。谢谢!

最佳答案

您在正确的轨道上,但是您尝试的语法已在 JavaScript 中用于 aliasing destructured variable names .

您可以像这样注释解构函数参数:

type ItemType = {
isEditor: boolean;
};

// The type needs to be specified after the parameter:
function doSomething({isEditor}: ItemType) {
const alias: boolean = isEditor;
}

// Inline type annotation works too:
function doSomethingElse({isEditor}: {isEditor: boolean}) {
const alias: boolean = isEditor;
}

// You can't type the destructured fields because that syntax is already used
// for aliasing the destructured parameters. Here, 'isEditor' is aliased to
// 'someOtherVariableName'.
function doSomethingWithAliasedArg({isEditor: someOtherVariableName}: ItemType) {
// Notice 'someOtherVariableName' is used instead of 'isEditor'
const alias: boolean = someOtherVariableName;
}

关于javascript - 将对象传递给函数时如何指定 TypeScript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67471304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com