从 class 创建派生类型,但省略构造函数(打字稿)

Create a derived type from class, but omit the constructor (typescript)

我有一个接口,class 定义如下:

interface Foo {
  constructor: typeof Foo;
}

class Foo {
  static bar = 'bar';

  constructor(data: Partial<Foo>) {
    Object.assign(this, data);
  }

  someMethod() {
    return this.constructor.bar;
  }

  prop1: string;
  prop2: number;
}

接口是必需的,因此 this.constructor 是强类型的。但是,它破坏了我将普通对象传递给 class 构造函数的能力:

const foo = new Foo({ prop1: 'asdf', prop2: 1234 });

// Argument of type '{ prop1: string; prop2: number; }' is not assignable to parameter of type 'Partial<Foo>'.
//  Types of property 'constructor' are incompatible.
//    Type 'Function' is not assignable to type 'typeof Foo'.
//      Type 'Function' provides no match for the signature 'new (data: Partial<Foo>): Foo'.

我理解错误消息,但我不知道解决方法。有什么方法可以让我传递一个普通对象的 Partial<Foo> 吗?这是一个游乐场:

Playground

看起来你想定义一个接口然后使用它,那么你必须在接口本身而不是 class 中定义属性。

interface Foo {
  prop1: string; // define your properties here
  prop2: number;
}

class Foo {
  static bar = 'bar';

  constructor(data: Partial<Foo>) {
    Object.assign(this, data);
  }

  someMethod() {
    return Foo.bar; // notice how I access static variables now
  }

}

const foo = new Foo({ prop1: 'asdf', prop2: 1234 });

Playground

我最终在这个精彩的答案中找到了我需要的东西:

how to remove properties via mapped type in TypeScript

该答案中的代码创建了一个包含 方法的派生类型。我需要做相反的事情。以下 NonMethods<T> 帮助程序创建了一个派生类型,其中删除了所有方法。

type NonMethodKeys<T> = ({[P in keyof T]: T[P] extends Function ? never : P })[keyof T];  
type NonMethods<T> = Pick<T, NonMethodKeys<T>>; 

Here's the Playground

这是从 class 创建派生类型的实际类型,省略构造函数(如问题标题中所示)并保留常规方法:

type NonConstructorKeys<T> = ({[P in keyof T]: T[P] extends new () => any ? never : P })[keyof T];
type NonConstructor<T> = Pick<T, NonConstructorKeys<T>>;

与问题 Foo 的用法:

type FooNonConstructorKeys = NonConstructorKeys<Foo>; // "prop1" | "prop2" | "someMethod"
type FooNonConstructor = NonConstructor<Foo>;