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
2 Answers
Reset to default 7I 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.