Tech Lead/Team Lead. Senior WebDev.
Intermediate Grade on Computer Systems-
High Grade on Web Application Development-
MBA (+Marketing+HHRR).
Studied a bit of law, economics and design
Location
Spain
Education
Higher Level Education Certificate on Web Application Development
To be honest, my example was rather abstract in the context of JavaScript, since there is no logic of operator overloading like in other programming languages like C#.
I was just looking for an illustrative example that could make sense from a purely logical point of view, and I ended up with this example :D
Nevertheless, I prepared another example that makes more sense in daily life. It is a serialization function that converts an object into different types (String, Uin8tArray, Stream) depending on the generic type parameter TFormat. The return type is derived depending on the value of TFormat:
typeJsonFormat={type:"json"};typeBinaryFormat={type:"binary"};typeStreamFormat={type:"stream"};typeFormat=JsonFormat|BinaryFormat|StreamFormat;typeSerializeReturnType<TFormatextendsFormat>=TFormatextendsJsonFormat?string:TFormatextendsBinaryFormat?Uint8Array:TFormatextendsStreamFormat?ReadableStream<Uint8Array>:never;functionserialize<TFormatextendsFormat>(obj:Record<string,unknown>,format:TFormat,):SerializeReturnType<TFormat>{if (format.type==="json"){constjsonString=JSON.stringify(obj);returnjsonStringasSerializeReturnType<TFormat>;}if (format.type==="binary"){consttextEncoder=newTextEncoder();constuint8array=textEncoder.encode(JSON.stringify(obj));returnuint8arrayasSerializeReturnType<TFormat>;}if (format.type==="stream"){consttextEncoder=newTextEncoder();constuint8array=textEncoder.encode(JSON.stringify(obj));conststream=newReadableStream({start(controller){controller.enqueue(uint8array);controller.close();},});returnstreamasSerializeReturnType<TFormat>;}thrownewError("Invalid format");}consts1=serialize({a:1,b:2},{type:"json"});// return type is stringconsts2=serialize({a:1,b:2},{type:"binary"});// return type is Uint8Arrayconsts3=serialize({a:1,b:2},{type:"stream"});// return type is Stream
Tech Lead/Team Lead. Senior WebDev.
Intermediate Grade on Computer Systems-
High Grade on Web Application Development-
MBA (+Marketing+HHRR).
Studied a bit of law, economics and design
Location
Spain
Education
Higher Level Education Certificate on Web Application Development
Yes, function overloading would also work in this case. I posted about function overloading in my previous post.
However, this post and example should simply illustrate that there are other ways that may be less verbose than overloading a function with multiple signatures.
Apologies for raining on your parade, but if your post is about "I made conditional return type work" because of "I solved the cause -- circular reference", then you're wrong.
The key part is that TypeScript simply doesn't unpack that T extends string? string : number for you when you're writing the function body. I'm not sure about the reason for it. This makes either as number or as string cannot satisfy the type T extends string? string : number.
Based on 1., to fix it you just mark those returns as any. Now, you get what you want from the returned object: it's either number or string depending on the argument.
So, why your workaround can work? By extracting the conditional return type into a type parameter R, and explicitly marking the return expression as R, you made the return type of that return the same as that of your function signature: both are R. So no error.
So, like it or not, both cases work with as any, playground. But I found your way a little bit counter-intuitive as you made the return type one of those generic parameters and always let TypeScript fill-out it for you. In that case, it shouldn't be a parameter.
While it's somewhat funny to see hacks with TS Types I've never found use-cases for this thingies in real life.
I'd rather do:
Which make each more reusable, less prone to error and overall more readable.
I've let a like, tho π cheers!
To be honest, my example was rather abstract in the context of JavaScript, since there is no logic of operator overloading like in other programming languages like C#.
I was just looking for an illustrative example that could make sense from a purely logical point of view, and I ended up with this example :D
Nevertheless, I prepared another example that makes more sense in daily life. It is a serialization function that converts an object into different types (String, Uin8tArray, Stream) depending on the generic type parameter
TFormat. The return type is derived depending on the value ofTFormat:TypeScript playground
Thank for your like! :)
Anytime! π
This one looks amazing, I believe it's pretty clear what the intended message was with this example, thank you ποΈ
That is what function overloading is for. tutorialsteacher.com/typescript/fu...
Yes, function overloading would also work in this case. I posted about function overloading in my previous post.
However, this post and example should simply illustrate that there are other ways that may be less verbose than overloading a function with multiple signatures.
No need for conditionals:
usage:
Doing conditionals with types makes the function more dependent with types, the more Types the more if blocks you will add into your function
Type 'string' is not assignable to type 'T extends string ? string : number'Why I'm I getting this error?
Is there as specific config I need?
I had the same issue. It seems that the generic parameter
Tcauses a circular reference when it is used as function type parameter and return type.You can refer to my second example that fixes this issue: Playground
That works Chris, thank you very much for the quick reply!
Sure, glad I could help :)
Apologies for raining on your parade, but if your post is about "I made conditional return type work" because of "I solved the cause -- circular reference", then you're wrong.
T extends string? string : numberfor you when you're writing the function body. I'm not sure about the reason for it. This makes eitheras numberoras stringcannot satisfy the typeT extends string? string : number.returnsas any. Now, you get what you want from the returned object: it's eithernumberorstringdepending on the argument.R, and explicitly marking the return expressionas R, you made the return type of thatreturnthe same as that of your function signature: both areR. So no error.So, like it or not, both cases work with
as any, playground. But I found your way a little bit counter-intuitive as you made the return type one of those generic parameters and always let TypeScript fill-out it for you. In that case, it shouldn't be a parameter.I hope this could help.
Nice to know information.
Interestingly for the original example Example compiler doesn't give any if return type is something like this -
return true as R;.Check out here - Playground
Looks like compiler allowing anything to pass.
For these second example compiler gives error - Serialization, probably due to type being inferred with each return statement?
Seems as strange hack
May I ask why?
Not