最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can conditional type in typescript depend on a value of itself? - Stack Overflow

programmeradmin1浏览0评论

Can I implement such type in typescript?

type Someone = {
  who: string;
}

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

Can I implement such type in typescript?

type Someone = {
  who: string;
}

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

Share Improve this question asked May 30, 2021 at 19:46 ZhenyaUsenkoZhenyaUsenko 4035 silver badges8 bronze badges 1
  • 1 The example doesn't make sense because a pile time type cannot depend on a runtime value. – Ingo Bürk Commented May 30, 2021 at 20:00
Add a ment  | 

2 Answers 2

Reset to default 7

I think a discriminated union could work:

type Me = {
  who: 'me',
  secret: string;
}

type Other = {
  who: 'other',
}

type Someone = Me | Other;

Yes, you can do so with the help of Generics, Distributive Conditional Types and Unions.

Below is a minimally working example:

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

Demo in TypeScript playground.

发布评论

评论列表(0)

  1. 暂无评论