r/typescript • u/bgxgklqa • Apr 23 '25
"isextendedby"
Hi! Need some help with some generics vodou! Thanks!
What I want:
class Container<T extends string> {
public moveFrom<U *isextendedby* T>(src: Container<U>) {
// Your code here.
}
}
so that
const cnt1 = new Container<"1" | "2">();
const cnt2 = new Container<"1">();
cnt1.moveFrom(cnt2);
but not
const cnt3 = new Container<"1" | "2" | "3">();
cnt1.moveFrom(cnt3);
Already tried all the various AI and they gave me non-working solutions.
11
Upvotes
13
u/Caramel_Last Apr 23 '25 edited Apr 23 '25
ok so `U extends T` will work but `U super T` doesn't exist in TS.
But TS has in/out keyword which you would be familiar with if you know Kotlin!
here is brief explanation
Here, T is "1" | "2"
now the question "does cnt2 satisfy Container<"1"|"2">?
cnt2 is Container<"1">
so what you want is "I want Container<"1"> to be a subtype of Container<"1"|"2">"
on the other hand
you want Container<"1"|"2"|"3"> not to be subtype of Container<"1"|"2">
In other words, you want Container<T> to be covariant on type T.
In simpler words, if T1 > T2 then Container<T1> > Container<T2>
in that case, in class type parameter, use `out T` to annotate this generic class is covariant on T. That is what I did.
On contrary if you use `in T`, now Container<T> is contravariant on type T.
In simpler words, if T1 > T2 then Container<T1> < Container<T2>
so now cnt1.moveFrom(cnt2); will not work and cnt1.moveFrom(cnt3) works.
Third case is Invariance. If Container<T> is invariant on T, then T1>T2 does not mean Container<T1> > Container<T2> nor, Container<T1> < Container<T2>. If you want to express that, use `in out T`. Which will invalidate both cnt1.moveFrom(cnt2); and cnt1.moveFrom(cnt3)
2
u/ptrxyz Apr 23 '25
This should do it:
1
u/YpsilonZX Apr 23 '25
Forgive me if I am wrong, but surely you could just have
src: Container<T>since a type which extends T will also satisfy T (I think that is correct?) ?2
u/Exact-Bass Apr 23 '25
Looks like you indeed want just
extendshere, unless your examples are the other way around. See eg.https://www.typescriptlang.org/play/?#code/MYGwhgzhAEDCD2A7ALmAlogpgJwDwBVpMAPZTRAExgmWwwHMA+aAbwChppgkyVoBeaFgDu0ALJgADgQA0QgK4BbAEY5GACgCUAbjYdoi+ADdMAMWzxFBAExFS5KtHwaI2YAC44PdFjz5rjJqs+pwAZvDY0OrciDTQANoA1pgAnnJGYCDymAC60PCh0K7AAHQxvMhB7Jw10GiF6gCEyAAWaBBlPOTIJS2Q6skpmlUhtdCt7Z0o3SUQmMgDqemZ2TqjnAC+RCBzwWM1Ex3lM3MLg8tZmNAA1ONtR10oJfTzi0ONa-sb60VuUxWzV7naAABk+NW+mzY3zYoXkiGAyDQSHGmBoAEYtHsuEg4sAUOiBEJMKIECgfDhcAAidFU6AAH2gVOsVI04JieJQtkEIi85IwlJprK0uk4+OQ6JKhhM5ks0S5axhcIRSJRZBo1ix1RxsWQXAJRN5ZNQArwQoZTJZbNFOs5yAAzIaSXyTb5qbSLcy6YyqfbheyCVLjGYLIp5Q7FUA
1
u/d0pe-asaurus Apr 23 '25
T extends U ? true : never
0
u/nach-o-man Apr 23 '25
Reminded me of "allopenissues" in Jira.