在TypeScript中,如何为具有静态方法作为参数的类定义类型?
我想定义一个类型,以便只接受特定形式的类作为参数 请告诉我在下面的代码中应该为在TypeScript中,如何为具有静态方法作为参数的类定义类型?,typescript,Typescript,我想定义一个类型,以便只接受特定形式的类作为参数 请告诉我在下面的代码中应该为Klass定义什么类型 class MyNumber { private __value: number; static from(value: any): MyNumber | null { if (typeof value === 'number') { return new MyNumber(value); } return null; } construc
Klass
定义什么类型
class MyNumber {
private __value: number;
static from(value: any): MyNumber | null {
if (typeof value === 'number') {
return new MyNumber(value);
}
return null;
}
constructor(value: number) {
this.__value = value;
}
to(): any {
return { type: 'NUMBER', value: this.__value };
}
}
class MyString {
private __value: string;
static from(value: any): MyString | null {
if (typeof value === 'string') {
return new MyString(value);
}
return null;
}
constructor(value: string) {
this.__value = value;
}
to(): any {
return { type: 'STRING', value: this.__value };
}
}
class MyBoolean {
private __value: boolean;
static from(value: any): MyBoolean | null {
if (typeof value === 'boolean') {
return new MyBoolean(value);
}
return null;
}
constructor(value: boolean) {
this.__value = value;
}
to(): any {
return { type: 'BOOLEAN', value: this.__value };
}
}
实现
func()
的最低可行类型如下:
function func(Klass, value: any): any {
const instance = Klass.from(value);
return instance ? instance.to() : null;
}
const output = hello(MyNumber, 3);
如果需要,可以使用接口重写,但这是一样的:
function func(Klass: { from(value: any): null | { to(): any } }, value: any): any {
const instance = Klass.from(value);
return instance ? instance.to() : null;
}
您正在使用的关于Klass
的唯一信息是,它有一个名为from()
的方法,该方法接受任何参数,并返回null
或带有to()
方法的新对象,该方法不接受任何参数并返回任何。这使示例代码能够正常工作:
interface Toable {
to(): any;
}
interface Fromable {
from(value: any): Toable | null;
}
function func(Klass: Fromable, value: any): any {
const instance = Klass.from(value);
return instance ? instance.to() : null;
}
但是,如果没有正确的from()
方法,则会拒绝使用参数:
const output = func(MyNumber, 3);
const output2 = func(MyString, 1); // accepts any, doesn't it?
const output3 = func(MyBoolean, 100);
它也不关心参数是否一定是构造函数,因为它不使用它来构造任何带有new
:
const bad = func(Date, 10); // error
// ------------> ~~~~
// Property 'from' is missing in type 'DateConstructor' but required in type 'Fromable'
const alsoBad = func({ from() { return "oopsie" } }, 123); // error
// ------------------> ~~~~
// Type 'string' is not assignable to type 'Toable | null'
这样看起来一切都很好。顺便说一句,我建议避免使用任何类型的,除非你写不出更具描述性的东西。但你没问这个,所以我就到此为止。希望有帮助;祝你好运
const okay = func({ from() { return null } }, 345); // okay
const output = func(MyNumber, 3);