class X<T> {
_t: T|null = null
}
class Y<T> {
_y: T|null = null
}
type ReplaceT<V extends unknown<any>, NewT> = unknown // How to do this
const x = new X<string>
const y = new Y<string>
// Assume that `x` is a type with 1 generic
type T1 = ReplaceT<typeof x, number> // X<number> expected
type T2 = ReplaceT<typeof x, boolean> // X<boolean> expected
type T3 = ReplaceT<typeof y, boolean> // Y<boolean> expected
这可能吗?
如果
V
是 X
或 Y
:,您可以使用条件类型
class X<T> {
_t: T|null = null
}
class Y<T> {
_y: T|null = null
}
type ReplaceT<V extends X<any> | Y<any>, NewT extends any> =
V extends X<any>
? X<NewT>
: V extends Y<any>
? Y<NewT>
: never;
const x = new X<string>
const y = new Y<string>
// Assume that `x` is a type with 1 generic
type T1 = ReplaceT<typeof x, number> // X<number> expected
type T2 = ReplaceT<typeof x, boolean> // X<boolean> expected
type T3 = ReplaceT<typeof y, boolean> // Y<boolean> expected