[英]How can I specify a TypeScript type when passing an object into a function?
I have a function:我有一个 function:
export default function AppNavbar({ isEditor }) {
I want to specify that isEditor
is boolean
.我想指定
isEditor
是boolean
。
I tried:我试过了:
export default function AppNavbar({ isEditor: boolean }) {
but that doesn't seem to work.但这似乎不起作用。 Any assistance is greatly appreciated.
非常感谢任何帮助。 Thanks!
谢谢!
You need to specify the type after the parameter, eg您需要在参数后指定类型,例如
export default function AppNavbar({ isEditor }: {isEditor: boolean}) {...
You are on the right track, however the syntax you tried is already used in JavaScript for aliasing destructured variable names .您走在正确的轨道上,但是您尝试的语法已在 JavaScript 中用于别名解构变量名称。
You can annotate destructured function parameters like this:您可以像这样注释解构的 function 参数:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.