如何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,
      },
      {
      . . . .
      }
    ];

其他回答

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 codeplex上有一个问题描述了这一点:支持对象初始化器。

如前所述,你已经可以通过在TypeScript中使用接口而不是类来做到这一点:

interface Name {
    givenName: string;
    surname: string;
}
class Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        givenName: "Bob",
        surname: "Smith",
    },
    age: 35,
};

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

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

可以影响类类型中强制转换的匿名对象。 奖励:在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
 };

我更倾向于这样做,使用(可选的)自动属性和默认值。您没有建议这两个字段是数据结构的一部分,所以这就是我选择这种方式的原因。

您可以在类中拥有属性,然后以通常的方式分配它们。显然,他们可能需要,也可能不需要,所以这也是另一回事。只是这是一个很好的语法糖。

class MyClass{
    constructor(public Field1:string = "", public Field2:string = "")
    {
        // other constructor stuff
    }
}

var myClass = new MyClass("ASD", "QWE");
alert(myClass.Field1); // voila! statement completion on these properties