3

Can I implement such type in typescript?

type Someone = {
  who: string;
}

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

1
  • 1
    The example doesn't make sense because a compile time type cannot depend on a runtime value. Commented May 30, 2021 at 20:00

2 Answers 2

7

I think a discriminated union could work:

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

type Other = {
  who: 'other',
}

type Someone = Me | Other;
Sign up to request clarification or add additional context in comments.

1 Comment

damn, that actually works for me and looks rly simple) thanks, just need to rewrote all interfaces to types now because this thing doesn't work with interfaces
7

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.

3 Comments

i think in your example it is required to specify "T" parameter, i would like it to take a value automatically e.g ``` const a: Someone = { who: "me", me: true } // ok const b: Someone = { who: "you", me: true } // error ```
@ZhenyaUsenko that is impossible because that would mean depending on a runtime value. Type checking only happens in the compile time, which is why you need to set the type constraint with T.
btw, the answer above works for me, thanks for the help anyways

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.