如何将 `{}` 转换或强制转换为 `T` 并在 TypeScript 中保留默认值?

How do I convert or cast `{}` to `T` and preserve default values In 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 时,您所做的就是对编译器说 "This thing is a Product even though it doesn't have the same properties as a Product"。

如果你想要默认值,你需要在你的 class 上放置一个构造函数,像这样:

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

有关类型断言(也称为类型转换)的更多信息,请阅读本文的 'Type Assertions' 部分:https://www.typescriptlang.org/docs/handbook/basic-types.html