如何init一个新的类在TS以这样的方式(在c#的例子,以显示我想要的):

// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ...  some code after

当前回答

我想要一个解决方案,将有以下:

所有数据对象都是必需的,并且必须由构造函数填充。 不需要提供默认值。 可以在类内部使用函数。

我是这样做的:

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的类

其他回答

对于更现代的TypeScript版本

类定义

    export class PaymentRequestDto {
      public PaymentSource: number;
      public PaymentCenterUid: string;
      public ConnectedUserUid: string;
    }

你有一些来自某处的价值观:

    const PaymentCenter= 'EA0AC01E-D34E-493B-92FF-EB2D66512345';
    const PaymentSource= 4;
    const ConnectedUser= '2AB0D13C-2BBE-46F5-990D-533067BE2EB3';

然后可以在使用强类型时初始化对象。

    const parameters: PaymentRequestDto = {
        PaymentSource,
        PaymentCenterUid: PaymentCenter,
        ConnectedUserUid: ConnectedUser,
    };

PaymentSource不需要名称字段说明符,因为使用的变量具有与字段相同的名称。

这也适用于数组。

    const parameters: PaymentRequestDto [] = [
      {
        PaymentSource,
        PaymentCenterUid: PaymentCenter,
        ConnectedUserUid: ConnectedUser,
      },
      {
      . . . .
      }
    ];

如果你使用的是旧版本的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的类

下面是一个结合了较短的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());

如果要创建新实例时没有设置初始值

1-你必须使用类而不是接口

2-你必须在创建类时设置初始值

export class IStudentDTO {
 Id:        number = 0;
 Name:      string = '';


student: IStudentDTO = new IStudentDTO();