Typescript Generics

I want to create a class who's signature is modified by function calls. For example;
const thing = new Thing(); // Thing<"">
const thing = new Thing(); // Thing<"">
const thing = new Thing(); // Thing<"foo" | "bar">
thing.add("foo"); // Thing<"foo" | "bar">
thing.add("bar"); // Thing<"foo" | "bar">
const thing = new Thing(); // Thing<"foo" | "bar">
thing.add("foo"); // Thing<"foo" | "bar">
thing.add("bar"); // Thing<"foo" | "bar">
I know that I can add to the generic by chaining .add().add() and having add's signature be add<T>(arg: T): Thing<ThingGeneric | T>, but I would like to be able to perform some kind of operation where if add is called with some parameter T, then thing always has been of a type such that it's first generic includes T. Is this even remotely possible?
3 Replies
Rägnar O'ock
Rägnar O'ock17mo ago
it is not possible because TS can't know when, where or even if the altering method is called. you will need to chain your methods, use a buffer const/var or cast the value to achieve what you want (I would advise against casting as you might run into jard to diagnose issues in the future
WillsterJohnson
WillsterJohnson17mo ago
I thought that might be the case The disconnect between data and types in TS is becoming more of a pain as I do more complex things
Rägnar O'ock
Rägnar O'ock17mo ago
I feel you, I had the same issue with a data parser, and I came to the hard truth same as you xD