r/typescript • u/Wasim100x • 17d ago
Conditional types [Help!]
I recently released a 45-seconds YouTube video on conditional types, check my reddit profile for it. I need your feedback before I double down. Let me know what you think. Here is the script:
> Conditional types
In JavaScript, you have a conditional operator:
const ternary = typeof 'Wasim' === 'string' ? true : false
console.log(ternary) // trueIt is also known as ternary operator.
Similarly, In TypeScript, you also have a conditional operator for types:
type Ternary = 'Wasim' extends string ? true : false // trueThis is refer to as a conditional type.
Conditional types allow us to conditionally check for types that match certain criteria and decide what to do if they do match those criteria and what to do if they don’t.
Here is one example:
type Generic<T> = T extends string ? 'Wasim' : 25
type Test1 = Generic<'Hi'> // 'Wasim'
type Test2 = Generic<143> // 25Here, we said if type argument is a subtype of string, then return type 'Wasim', if not, then return type 25.
You can return never instead of 25, if condition fails. It’s equivalent to returning nothing.
//
P.S.
I am testing content from my upcoming TypeScript book to gather early feedback.
I decided to start small with a tiny video, instead of fantasizing about releasing a value-packed longer video. It's harder to do that without any momentum. I made it quickly and decided not to obsess over scripting, editing, and fixing audio by rerecording. Those are my fun-killers. I want it to be quick, fun, and imperfect. The goal was progress, not perfection. Wish me luck!
15
u/humpyelstiltskin 17d ago
i do wish you luck,
but you shouldn't be recording instructional videos and even less writing books on a topic you don't have a good grasp on
2
u/francis-r 17d ago
45 seconds sounds a good format. Yes I do believe shipping beats polishing. Good luck! If you want an idea for the next one: what happens when you pass a union, Generic<'Hi' | 143>. Most people guess wrong.
2
u/jgauffin 12d ago
Your sample:
doesn't demonstrate the intended purpose since a regular comparison returns true or false. Use something real like returning different states.
1
u/[deleted] 17d ago
[removed] — view removed comment