使用 Typescript 用剩余和类型解构对象

发布于 2025-01-17 07:50:27 字数 879 浏览 3 评论 0原文

解释器表示 humanProps 的类型为 humanProps: { humanProps: IHumanProps} 。

如何正确设置传播类型,以使 humanPros 具有 IHumanProps 类型?

示例:

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

如何使用扩展语法解构对象并指定类型?我在网上找不到有关此具体案例的任何信息。

我收到的确切错误是 VSCode(或者更确切地说是 linter)说解构的 humanProps 类型不是 IHumanProps 类型,而是类型 { humanProps: { humanProps: IHumanProps}},这是不正确的。我认为这可能是 VSCode/ESLint 的问题。

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 destructure an object using spread syntax and specify the types? I couldn't find any information online about this specific case.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小耗子 2025-01-24 07:50:27

我建议您重写类型以使其更加清晰


type Name = {
  name: string;
}

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

type Human = Name & HumanProps;

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

现在,为了破坏 人类 对象,您只需执行以下操作

const {name, ...humanProps} = human

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文