如何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 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

其他回答

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

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

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

初始化一个类而不重新声明默认值的所有属性:

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)
  }
}

这结合了一些已经很好的答案

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操场

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

这是如何……

function as_<T>(o: T) { return o; };
// ... some code before
return as_<MyClass>({ Field1 = "ASD", Field2 = "QWE" });
// ...  some code after