如何init一个新的类在TS以这样的方式(在c#的例子,以显示我想要的):
// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after
如何init一个新的类在TS以这样的方式(在c#的例子,以显示我想要的):
// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after
当前回答
这是我找到的最好的解决办法。
声明一个可以用作装饰器的函数。我称之为自动反射
export function AutoReflect<T extends { new(...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
constructor(...args: any[]) {
super(args)
if (typeof args[0] === 'object') {
Object.assign(this, args[0]);
}
}
};
}
这样做的目的是在构造函数中期望一个对象,并将成员分配给类实例。 在类声明中使用这个
interface IPerson {
name: string;
age: number;
}
@AutoReflect
class Person implements IPerson {
name: string;
number: number;
constructor(model?: Partial<IPerson>){}
}
在模型的构造函数中,您可以使模型成为可选的,并且在使用Partial时,您可以在不设置所有属性值的情况下新建实例
new Person({
name: 'Santa'
});
这个方法创建了一个您想要的类的新实例,并且对它有c#对象初始化的感觉。
其他回答
可以有一个带有可选字段(用?标记)的类和一个接收同一类实例的构造函数。
class Person {
name: string; // required
address?: string; // optional
age?: number; // optional
constructor(person: Person) {
Object.assign(this, person);
}
}
let persons = [
new Person({ name: "John" }),
new Person({ address: "Earth" }),
new Person({ age: 20, address: "Earth", name: "John" }),
];
在这种情况下,您将不能省略必需的字段。这为您提供了对对象构造的细粒度控制。
你可以使用Partial类型的构造函数,如其他答案中所述:
public constructor(init?:Partial<Person>) {
Object.assign(this, init);
}
问题是所有字段都是可选的,在大多数情况下都不可取。
如果你使用的是旧版本的typescript < 2.1,那么你可以使用类似于下面的方法,基本上是将任意类型转换为类型化对象:
const typedProduct = <Product>{
code: <string>product.sku
};
注意:使用此方法只适用于数据模型,因为它将删除 对象中的所有方法。它基本上是将任何对象转换为a 类型的对象
这是如何……
function as_<T>(o: T) { return o; };
// ... some code before
return as_<MyClass>({ Field1 = "ASD", Field2 = "QWE" });
// ... some code after
初始化一个类而不重新声明默认值的所有属性:
class MyClass{
prop1!: string //required to be passed in
prop2!: string //required to be passed in
prop3 = 'some default'
prop4 = 123
constructor(opts:{prop1:string, prop2:string} & Partial<MyClass>){
Object.assign(this,opts)
}
}
这结合了一些已经很好的答案
这里有一个解决方案:
不强迫你让所有字段都是可选的(不像Partial<…>) 区分类方法和函数类型的字段(不同于OnlyData<…>解决方案) 通过定义Params接口提供了一个很好的结构 不需要重复变量名和类型不止一次
唯一的缺点是一开始看起来比较复杂。
// Define all fields here
interface PersonParams {
id: string
name?: string
coolCallback: () => string
}
// extend the params interface with an interface that has
// the same class name as the target class
// (if you omit the Params interface, you will have to redeclare
// all variables in the Person class)
interface Person extends PersonParams { }
// merge the Person interface with Person class (no need to repeat params)
// person will have all fields of PersonParams
// (yes, this is valid TS)
class Person {
constructor(params: PersonParams) {
// could also do Object.assign(this, params);
this.id = params.id;
this.name = params.name;
// intellisence will expect params
// to have `coolCallback` but not `sayHello`
this.coolCallback = params.coolCallback;
}
// compatible with functions
sayHello() {
console.log(`Hi ${this.name}!`);
}
}
// you can only export on another line (not `export default class...`)
export default Person;