如何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
当前回答
可以影响类类型中强制转换的匿名对象。 奖励:在visual studio中,你可以这样受益于智能感知:)
var anInstance: AClass = <AClass> {
Property1: "Value",
Property2: "Value",
PropertyBoolean: true,
PropertyNumber: 1
};
编辑:
警告:如果类有方法,类的实例将得不到它们。如果AClass有构造函数,它将不会被执行。如果使用instanceof AClass,则会得到false。
总之,应该使用接口而不是类。 最常见的用途是声明为普通旧对象的域模型。 实际上,对于域模型,您应该更好地使用接口而不是类。接口在编译时用于类型检查,与类不同,接口在编译期间被完全删除。
interface IModel {
Property1: string;
Property2: string;
PropertyBoolean: boolean;
PropertyNumber: number;
}
var anObject: IModel = {
Property1: "Value",
Property2: "Value",
PropertyBoolean: true,
PropertyNumber: 1
};
其他回答
更新
写完这个答案后,更好的方法出现了。请看下面的其他答案,有更多的投票和更好的答案。我不能删除这个答案,因为它被标记为已接受。
旧的答案
TypeScript codeplex上有一个问题描述了这一点:支持对象初始化器。
如前所述,你已经可以通过在TypeScript中使用接口而不是类来做到这一点:
interface Name {
givenName: string;
surname: string;
}
class Person {
name: Name;
age: number;
}
var bob: Person = {
name: {
givenName: "Bob",
surname: "Smith",
},
age: 35,
};
初始化一个类而不重新声明默认值的所有属性:
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)
}
}
这结合了一些已经很好的答案
这是我找到的最好的解决办法。
声明一个可以用作装饰器的函数。我称之为自动反射
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#对象初始化的感觉。
这里有一个解决方案:
不强迫你让所有字段都是可选的(不像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;
如果要创建新实例时没有设置初始值
1-你必须使用类而不是接口
2-你必须在创建类时设置初始值
export class IStudentDTO {
Id: number = 0;
Name: string = '';
student: IStudentDTO = new IStudentDTO();