如何将“{}”转换或转换为“T”并在 TypeScript 中保留默认值



假设我有三个属性及其默认值的Product。当{}中没有值时,如何将{}转换或转换为默认值Product

export class Product{
  Price:number=20;
  Label:string="No name";
  Details:string="no desc";
}
let laptop = {Label:'Laptop'} as Product;
//I would like to get this laptop ={Label:'Label',Price:20,Details:'no desc'}

这在类型转换中是不可能的。当你转换一个对象时,你所做的只是as Product编译器说,"这个东西是一个产品,即使它与产品没有相同的属性"。

如果你想要默认值,你需要在你的类上放置一个构造函数,如下所示:

export class Product {
  price: number;
  label: string;
  details: string;
  constructor(obj: {price?: number, label?: string, details?: string}) {
    this.price = obj.price || 20;
    this.price = obj.label || "No name";
    this.details = obj.details || "No description";
  }
}

然后,您可以传递任何部分配置对象,并设置其他默认值。

let laptop = new Product({label: 'Laptop'}); 
// {label: 'Laptop', price: 20, details: 'No description'}

现在,laptop将自动为类型 Product,您甚至不必强制转换它。

提示: 可以使用 Partial 类型使键入构造函数参数更容易。

type Partial<T> = {
  [P in keyof T]?: T[P];
}

然后,构造函数参数将如下所示constructor(obj: Partial<Product>)

有关类型断

言(也称为类型转换(的详细信息,请阅读本文的"类型断言"部分:https://www.typescriptlang.org/docs/handbook/basic-types.html。

最新更新