如何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
当前回答
type ExcludeMethods<T> = Pick<T, { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]>;
class MyClass {
public name!: string;
public age!: number;
public optional?: boolean;
private yep: string = "";
constructor(props: ExcludeMethods<typeof MyClass.prototype>) {
Object.assign(this, props);
}
public method() {
}
}
const thing = new MyClass({
name: "bob",
age: 15
});
TS操场
其他回答
我建议一种不需要Typescript 2.1的方法:
class Person {
public name: string;
public address?: string;
public age: number;
public constructor(init:Person) {
Object.assign(this, init);
}
public someFunc() {
// todo
}
}
let person = new Person(<Person>{ age:20, name:"John" });
person.someFunc();
重点:
Typescript 2.1不需要,Partial<T>不需要 它支持函数(与不支持函数的简单类型断言相比)
下面是一个结合了较短的Object应用程序的解决方案。赋值来更紧密地模拟原始的c#模式。
但首先,让我们回顾一下到目前为止提供的技术,包括:
复制接受对象的构造函数,并将其应用于object .assign 复制构造函数中的一个聪明的Partial<T>技巧 针对POJO使用“强制转换” 利用对象。create而不是Object.assign
当然,每种方法都有其优点和缺点。修改目标类以创建复制构造函数可能并不总是一种选择。而“强制转换”会丢失与目标类型相关的所有函数。对象。Create似乎不那么吸引人,因为它需要相当冗长的属性描述符映射。
简短、通用的回答
因此,这里还有另一种更简单的方法,它维护了类型定义和相关的函数原型,并更紧密地模拟了预期的c#模式:
const john = Object.assign( new Person(), {
name: "John",
age: 29,
address: "Earth"
});
就是这样。在c#模式上唯一增加的是Object。赋值时加上2个括号和一个逗号。查看下面的工作示例,确认它维护了类型的函数原型。不需要构造函数,也不需要巧妙的技巧。
工作示例
这个例子展示了如何使用近似c#字段初始化器来初始化一个对象:
人物{ 名称:string = "; 地址:string = "; 年龄:0; aboutMe () { 返回' Hi, I'm ${this.name}, age ${this.name。年龄}和来自${this.address} '; } } // typescript字段初始化式(维护"type"定义) const john =对象。assign(new Person(), { 名称:“约翰”, 年龄:29岁 地址:“地球” }); //初始化对象维护aboutMe()函数原型 console.log(john.aboutMe());
初始化一个类而不重新声明默认值的所有属性:
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)
}
}
这结合了一些已经很好的答案
如果你使用的是旧版本的typescript < 2.1,那么你可以使用类似于下面的方法,基本上是将任意类型转换为类型化对象:
const typedProduct = <Product>{
code: <string>product.sku
};
注意:使用此方法只适用于数据模型,因为它将删除 对象中的所有方法。它基本上是将任何对象转换为a 类型的对象
我想要一个解决方案,将有以下:
所有数据对象都是必需的,并且必须由构造函数填充。 不需要提供默认值。 可以在类内部使用函数。
我是这样做的:
export class Person {
id!: number;
firstName!: string;
lastName!: string;
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
constructor(data: OnlyData<Person>) {
Object.assign(this, data);
}
}
const person = new Person({ id: 5, firstName: "John", lastName: "Doe" });
person.getFullName();
构造函数中的所有属性都是强制性的,如果省略这些属性将会导致编译器错误。
它依赖于OnlyData从必需的属性中过滤出getFullName(),它的定义如下:
// based on : https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c
type FilterFlags<Base, Condition> = { [Key in keyof Base]: Base[Key] extends Condition ? never : Key };
type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];
type SubType<Base, Condition> = Pick<Base, AllowedNames<Base, Condition>>;
type OnlyData<T> = SubType<T, (_: any) => any>;
目前这种方式的局限性:
需要TypeScript 2.8 具有getter /setter的类