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;
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
T.