如何替换自定义泛型类型中的泛型类型

问题描述 投票:0回答:1
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

游乐场

这可能吗?

typescript typescript-typings typescript-generics
1个回答
0
投票

如果

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
© www.soinside.com 2019 - 2024. All rights reserved.