'typescript: deconstruct object with rest and types

The interpreter says that humanProps is of type humanProps: {humanProps: IHumanProps}.

How can I set the type for the spread correctly so that humanPros has the type IHumanProps?

Example:

interface IName {
  name: string
}

interface IHumanProps {
  hobby: string,
  age: number
}

interface IHuman extends IName, IHumanProps {}

const human: IHuman = {
  name: 'Linda',
  hobby: 'reading',
  age: 99
}

const { name, ...humanProps }: { name: string, humanProps: IHumanProps } = human;

console.log(name);
console.log(humanProps);

How can I deconstruct an object with the spread operator and specify the types? I couldn't find any information online about this specific case.

[Edit]: The exact error I was receiving was that VSCode (or maybe rather the linter) were saying that the deconstructed humanProps were not of the type IHumanProps but rather of type {humanProps: {humanProps: IHumanProps}}, which is not correct. I assume this could be have been an issue with VSCode/ESLint. Thank you all for the fast responses!



Solution 1:[1]

I would suggest you to rewrite the types to be more clear


type Name = {
  name: string;
}

type HumanProps = {
  hobby: string;
  age: number;
}

type Human = Name & HumanProps;

const human: Human = {
  name: 'Linda',
  hobby: 'reading',
  age: 99
}

Now, in order to destruct the human object you simply have to do the following

const {name, ...humanProps} = human

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nullable