如何将 typeof 用于泛型参数值?
How to use typeof for generic argument value?
我想定义一个接口,我在其中传递通用参数,然后使用传递的值并同时输入它的类型。
这与我想要完成的类似:
interface ComponentProps<T extends new (...args: any) => any> {
params: ConstructorParameters<typeof T>[0]
onSubmit: (op: T) => void
}
由于参数是一个值,所以会出现此错误:
'T' only refers to a type, but is being used as a value here.ts(2693)
我可以定义这个接口并将其用作:
interface ComponentProps<T> {
onSubmit: (op: T) => void
}
type CustomComponentProps = ComponentProps<ClassA> // I can directly pass the class
或
interface ComponentProps<T extends new (...args: any) => any> {
params: ConstructorParameters<T>[0]
}
type CustomComponentProps = ComponentProps<typeof ClassA> // I need to pass typeof the class
这可能是一个我还没有弄清楚的简单问题,但是是否可以将 class 本身作为通用参数传递,然后在接口中获取其类型而不需要单独传递它们作为 ComponentProps<ClassA, typeof ClassA>
?
is it possible to pass the class itself as a generic argument and then get its type inside the interface without needing to pass them separately
您可以使用 InstanceType 获取 class 类型的实例类型:
class ClassA {
constructor(public a: string) { }
}
interface ComponentProps<T extends new (...args: any) => any> {
params: ConstructorParameters<T>[0]
onSubmit: (op: InstanceType<T>) => void
}
declare const props: ComponentProps<typeof ClassA>
props.params // params: string
props.onSubmit(new ClassA("foo") ) // onSubmit: (op: ClassA) => void
我想定义一个接口,我在其中传递通用参数,然后使用传递的值并同时输入它的类型。
这与我想要完成的类似:
interface ComponentProps<T extends new (...args: any) => any> {
params: ConstructorParameters<typeof T>[0]
onSubmit: (op: T) => void
}
由于参数是一个值,所以会出现此错误:
'T' only refers to a type, but is being used as a value here.ts(2693)
我可以定义这个接口并将其用作:
interface ComponentProps<T> {
onSubmit: (op: T) => void
}
type CustomComponentProps = ComponentProps<ClassA> // I can directly pass the class
或
interface ComponentProps<T extends new (...args: any) => any> {
params: ConstructorParameters<T>[0]
}
type CustomComponentProps = ComponentProps<typeof ClassA> // I need to pass typeof the class
这可能是一个我还没有弄清楚的简单问题,但是是否可以将 class 本身作为通用参数传递,然后在接口中获取其类型而不需要单独传递它们作为 ComponentProps<ClassA, typeof ClassA>
?
is it possible to pass the class itself as a generic argument and then get its type inside the interface without needing to pass them separately
您可以使用 InstanceType 获取 class 类型的实例类型:
class ClassA {
constructor(public a: string) { }
}
interface ComponentProps<T extends new (...args: any) => any> {
params: ConstructorParameters<T>[0]
onSubmit: (op: InstanceType<T>) => void
}
declare const props: ComponentProps<typeof ClassA>
props.params // params: string
props.onSubmit(new ClassA("foo") ) // onSubmit: (op: ClassA) => void