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

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

当前回答

对于更现代的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,
      },
      {
      . . . .
      }
    ];

其他回答

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

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

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

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


student: IStudentDTO = new IStudentDTO();
type ExcludeMethods<T> = Pick<T, { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]>;

class Person{
  name: string = "N/A";
  age: number = 0;
  gender?: "male" | "female"

  constructor(init?:ExcludeMethods<Person>){
    Object.assign(this, init);
  }

  Describe(){return `${this.name} ${this.age} ${this.gender ?? ""}` }
}

var p1 = new Person();
var p2 = new Person({
  name: "John",
  age: 20
});
var p3 = new Person({
  name: "Mary",
  age: 25,
  gender: "female"
});

console.log(p1.Describe()) // N/A 0
console.log(p2.Describe()) // John 20
console.log(p3.Describe()) // Mary 25 female

最简单的方法是使用类型强制转换。

return <MyClass>{ Field1: "ASD", Field2: "QWE" };

更新

写完这个答案后,更好的方法出现了。请看下面的其他答案,有更多的投票和更好的答案。我不能删除这个答案,因为它被标记为已接受。


旧的答案

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,
};

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

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

我是这样做的:

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