如何将“{}”转换或强制转换为“T”,并在TypeScript中保留默认值?
假设我有如何将“{}”转换或强制转换为“T”,并在TypeScript中保留默认值?,typescript,typescript-2.5,Typescript,Typescript 2.5,假设我有产品,有三个属性及其默认值。当{}中没有值时,如何根据默认值将{}转换或强制转换为产品 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,Deta
产品
,有三个属性及其默认值。当{}
中没有值时,如何根据默认值将{}
转换或强制转换为产品
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'}
这在类型转换中是不可能的。当你将一个对象
转换为产品时,你要做的就是告诉编译器,“这个东西是一个产品,尽管它的属性与产品不同”
如果需要默认值,则需要在类上放置构造函数,如下所示:
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'}
现在,笔记本电脑
将自动成为产品
类型,您甚至不必强制转换它
提示:您可以使用Partial
类型来简化构造函数参数的键入
type Partial<T> = {
[P in keyof T]?: T[P];
}
类型部分={
[P在keyof T]?:T[P];
}
然后您的构造函数参数看起来像构造函数(obj:Partial)
有关类型断言(又称类型转换)的更多信息,请阅读本文的“类型断言”部分: