首页 > 解决方案 > 打字稿中的条件类型可以依赖于自身的值吗?

问题描述

我可以在打字稿中实现这种类型吗?

type Someone = {
  who: string;
}

type Someone = Someone.who === "me" ? Someone & Me : Someone;

标签: javascripttypescript

解决方案


是的,您可以借助泛型分布条件类型联合来实现。

下面是一个最低限度的工作示例:

type Someone<T extends string> = {
    who: T;
}

type Me = {
    me: boolean;
}

type Thisone<T extends string> = T extends 'me' ? Someone<T> & Me : Someone<T>;

function whoami<T extends string>(who: T) {
    return {
        who,
        me: who === 'me' ? true : undefined
    } as Thisone<T>
}

const a = whoami('you');
const b = whoami('me');

a.who;  // ok
a.me;   // error

b.who;  // ok
b.me;   // ok

在 TypeScript 操场上演示


推荐阅读