Shamoon
Shamoon

Reputation: 43609

How can I specify a TypeScript type when passing an object into a function?

I have a function:

export default function AppNavbar({ isEditor }) {

I want to specify that isEditor is boolean.

I tried:

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

but that doesn't seem to work. Any assistance is greatly appreciated. Thanks!

Upvotes: 3

Views: 85

Answers (2)

scupit
scupit

Reputation: 844

You are on the right track, however the syntax you tried is already used in JavaScript for aliasing destructured variable names.

You can annotate destructured function parameters like this:

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;
}

Upvotes: 4

Rob Bailey
Rob Bailey

Reputation: 981

You need to specify the type after the parameter, e.g.

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

Upvotes: 3

Related Questions