简体   繁体   English

当我需要更改对象中的属性类型时,如何正确使用 TypeScript

[英]How do I work with TypeScript correctly when I need to change a type of a property in an object

I have this class that represents JSON incoming from POST request.我有这个类表示从 POST 请求传入的 JSON。

class MilkCarton {
  company: string;
  price: number;
  expiredAt?: string;
  // ...20 more properties
}

Before I store it in my mongoDB database, I want to change the type of expiredAt to Date , so I have another class that represents the schema of the database.在我将它存储在我的 mongoDB 数据库中之前,我想将expiredAt的类型expiredAtDate ,所以我有另一个代表数据库模式的类。

class MilkCartonSchema: {
  company: string;
  price: number;
  expiredAt?: Date;
  // ...20 more properties
}

expiredAt can be null, I want to create an object that copies the object of type MilkCarton but has its expiredAt converted to Date expiredAt可以为 null,我想创建一个对象来复制MilkCarton类型的对象,但将其expiredAt转换为Date

prepareMilkForDb(milk: MilkCarton): MilkCartonSchema {
  const preparedMilk = {
    ...milk,
  }

  if (milk.expiredAt) {
    preparedMilk.expiredAt = new Date(milk.expiredAt)
  }

  return preparedMilk;
}

But I run into an error because preparedMilk has already inferred its type and has expiredAt as string , it can't be turned into Date from TypeScript perspective if it's string .但是我碰到一个错误,因为preparedMilk已经推断出它的类型,并具有expiredAtstring ,它不能变成Date从打字稿角度来看,如果它的string But I want it to turn into Date , what is the approach to do that correctly in TypeScript?但我希望它变成Date ,在 TypeScript 中正确执行此操作的方法是什么?

EDIT: I ended up going with:编辑:我最终选择了:

prepareMilkForDb(milk: MilkCarton): MilkCartonSchema {
  const preparedMilk = {
    ...milk,
    ...(milk.expiredAt && {
      expiredAt: new Date(milk.expiredAt)
    }),
  }

  return preparedMilk;
}

This works, but isn't exactly what I wished for, if I had another example with 3 different deep nested ISO string properties that need converting to Date (and backwards) it would be very dirty to do this workaround.这有效,但并不完全是我所希望的,如果我有另一个示例,其中包含 3 个不同的深度嵌套 ISO string属性,需要转换为Date (和向后),那么执行此解决方法将非常脏。

Does this work for you?这对你有用吗?

interface MilkCarton {
    company: string;
    price: number;
    expiredAt?: string;
    // ...20 more properties
}

interface MilkCartonSchema {
    company: string;
    price: number;
    expiredAt?: Date;
    // ...20 more properties
}

const prepareMilkForDb = (milk: MilkCarton): MilkCartonSchema => {
    return {
        ...milk,
        expiredAt: milk.expiredAt == null ? undefined : new Date(milk.expiredAt)
    };
}

Typescript sandbox 打字稿沙箱

Note: I changed the classes to interface, I don't know if that's ok or not?注意:我把类改成了接口,不知道这样行不行?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么需要两次键入此命令才能使其在Iscript 2的Typescript中工作? - Why do I need to type this command twice for it to work in Typescript, Ionic 2? 在 TypeScript 中,我如何在 go 中向接口中的 object 类型添加属性? - In TypeScript, How do I go about adding a property to an object type in an Interface? 打字稿:类型“{}”不能指定为“选择”类型 <T, K> &#39;,如何正确输入javascript`pick`功能? - Typescript: Type '{}' is not assignable to type 'Pick<T, K>', how do I type javascript `pick` function correctly? 我需要如何更改这些 TypeScript mixin 类型定义,以便允许定义允许 class 扩展特征的 mixin? - How do I need to change these TypeScript mixin type definitions in order to allow the definition of mixins that allow a class to extend the trait? 在 Typescript 中,如何在存储然后从数组访问所述对象时维护对象类型? - In Typescript, how do I maintain an objects type when storing and then accessing said object from an array? 如何解决&#39;属性&#39;宽度&#39;在类型&#39;HTMLElement&#39;上不存在。&#39; 当使用// @ ts-check在vscode中键入检查Javascript(NOT Typescript)时? - How do I solve 'Property 'width' does not exist on type 'HTMLElement'.' when type checking Javascript (NOT Typescript) using // @ts-check in vscode? 在JavaScript中创建全局变量时是否需要指定对象类型? - Do I need to specify object type when creating globals in Javascript? 我如何在 Typescript 中对这个 object 进行类型检查 - How do I type-check this object in Typescript 将 object 传递给 function 时,如何指定 TypeScript 类型? - How can I specify a TypeScript type when passing an object into a function? 我一直发现自己在使用 TypeScript 时遇到了同样的错误。 当我需要返回一个执行后已知的类型时,我该怎么办? - I keep finding myself in the same error with TypeScript. What do I do when I need to return a type that will be known after execution?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM