Home > Software engineering >  Vue 3 TypeScript optional props object checking length - error
Vue 3 TypeScript optional props object checking length - error

Time:09-27

I need props to be an object that is optional.

interface MyObject { id: string| number, name: string, namePlural: string}
interface Props { preloadInputs?: MyObject}

... // check if preloadInputs is not empty:

onMounted(() => {if (!(Object.keys(props.preloadInputs).length === 0)) {...} })

VSCode's error for the props.preloadInputs is:

I get an error:

No overload matches this call Overload 1 of 2, ' (o: {}): string[]', gave the following error. Overload 2 of 2, ' (o: object): string[]', gave the following error.ts (2769)

I am new to Vue and TS, so there must be something I am missing.

CodePudding user response:

You defined preloadInputs to be optional so it can have a value of undefined. Object.keys() does not accept undefined as the argument. That's why you get the error Type 'undefined' is not assignable to type '{}'.

We could use the nullish coalescing operator to solve this problem.

Object.keys(props.preloadInputs ?? {}).length === 0

If props.preloadInputs is undefined, an empty object gets passed to Object.keys().

  • Related