【问题标题】:Typescript - clone an object and cast into another type打字稿 - 克隆一个对象并转换为另一种类型
【发布时间】:2021-02-04 19:11:21
【问题描述】:

我正在尝试克隆一个无类型的对象。我想在克隆时投射它。 这是一个非常简单的代码:

const typedOject: type123 = {...untypedObject} as type123;
typeObject.a = 1;

export interface type123 {
   a: number;
   b: number;
}

但是编译器抱怨: 类型“any[]”上不存在属性“a”

那么,为什么新对象的类型是 any?

谢谢

【问题讨论】:

  • 对于这样的任务,我通常会编写一个转换器函数,它接受一个任意对象并检查其属性 + 构建返回类型
  • 另外,我没有看到你上面的代码中有y
  • 复制自开发代码。修正了错字。
  • 我明白了。我已经添加了答案,如果您有任何其他问题,请告诉我

标签: typescript


【解决方案1】:

这些类型的转换对于处理传入的 API 数据很常见

以下是我处理这些类型的转换的方式:

类型/GithubRepo.ts

export interface GithubRepo {
  id: number;
  name: string;
  description: string;
  stars: number;
}

export const convertIntoGithubRepo = (githubRepoFragment: any): GithubRepo => ({
  id: githubRepoFragment.id,
  name: githubRepoFragment.name,
  description: githubRepoFragment.description || '',
  stars: githubRepoFragment.stargazers_count,
});

用法


import { convertIntoGithubRepo } from 'types/GithubRepo';


const githubRepo = convertIntoGithubRepo(someGithubRepoFragment);

对于这个例子,我定义了一个类型,然后定义了将any类型的对象复制到GithubRepo类型的方法

在此转换过程中,我们可以看到我正在检查 any 对象上的描述是否存在,如果有则添加一个空白

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多