gpt4 book ai didi

javascript - 从类创建派生类型,但省略构造函数( typescript )

转载 作者:行者123 更新时间:2023-11-30 19:10:17 24 4
gpt4 key购买 nike

我有一个这样定义的接口(interface)和类:

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

接口(interface)是必要的,这样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'.

我理解错误消息,但我不知道解决方法。有什么办法可以得到 Partial<Foo>这允许我传递一个普通对象?这是一个 Playground :

Playground

最佳答案

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

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

关于javascript - 从类创建派生类型,但省略构造函数( typescript ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58562612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com