Rya*_*ale 3 javascript derived-types typescript
我有一个这样定义的接口和类:
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;
}
Run Code Online (Sandbox Code Playgroud)
接口是this.constructor强类型所必需的。但是,它破坏了我将普通对象传递给类构造函数的能力:
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'.
Run Code Online (Sandbox Code Playgroud)
我理解该错误消息,但不知道解决方法。有什么方法Partial<Foo>可以让我传递一个普通对象吗?这是一个游乐场:
这是从省略构造函数(如问题标题中所示)并保留常规方法的类创建派生类型的实际类型:
type NonConstructorKeys<T> = ({[P in keyof T]: T[P] extends new () => any ? never : P })[keyof T];
type NonConstructor<T> = Pick<T, NonConstructorKeys<T>>;
Run Code Online (Sandbox Code Playgroud)
Foo与问题中的一起使用:
type FooNonConstructorKeys = NonConstructorKeys<Foo>; // "prop1" | "prop2" | "someMethod"
type FooNonConstructor = NonConstructor<Foo>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5563 次 |
| 最近记录: |