Type alias ReplaceType<T, TFrom, TTo>

ReplaceType<T, TFrom, TTo>: {
    [P in keyof T]: T[P] extends TFrom
        ? TTo
        : ReplaceType<T[P], TFrom, TTo>
}

TypeScript 類型,把 T 所有類型為 TFrom 的成員替換成 TTo

所有層級都會替換。TFrom 必須TTo 不相容

Type Parameters

  • T

    類型

  • TFrom

    要替換掉的類型

  • TTo

    要替換成的類型

Example

class Dog { bark() {} };
class Cat { meow() {} };
type CatFan = { pet: Cat, friend: { pet: Cat } };
type DogFan = ReplaceType<CatFan, Cat, Dog> // => { pet: Dog, friend: { pet: Dog } }

const dogOwner = { pet: new Dog(), friend: { pet: new Cat() } };
dogOwner satisfies CatFan; // ❌ Error: Dog is not assignable to type Cat
dogOwner satisfies DogFan; // ❌ Error: Cat is not assignable to type Dog
const dogFan = { pet: new Dog(), friend: { pet: new Dog() } };
dogFan satisfies DogFan; // ✅

Generated using TypeDoc