DEV Community

Cover image for 10 Advanced TypeScript Concepts Every Developer Should Know

10 Advanced TypeScript Concepts Every Developer Should Know

Niharika Goulikar on November 14, 2024

TypeScript is a modern programming language often preferred over JavaScript for its added type safety. In this article, I'll share the top 10 TypeS...
Collapse
 
eric_b_67cb420d1a0eddc900 profile image
Eric B • Edited

Nice list, but this is wrong;

While TypeScript primarily focuses on type checking at compile time, we can still leverage TypeScript operators to inspect types during runtime.

TypeScript is only a static type checker that checks at compile time (or rather transpilation time).

typeof is a JavaScript feature, not a TypeScript feature. Even though javascript does not have strict static typing, every language must still have the concept of types at some point because hardware instructions are different for say string operations and numerical operations. Typescripts type system is something separate from that. It's ONLY a static checker performed before code is run, and TypeScript-specific code features will never run at runtime.

Collapse
 
anisaa_96baa257 profile image
Anisa

Loved the explanation on dependency injection!

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

The covariance example is incorrect. Who else can spot it? I see many comments on the wonders of the article, many reactions too, but nobody notices it? Hmmm. People, what's up?

Collapse
 
niharikaa profile image
Niharika Goulikar

sorry! I just fixed it .

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Still wrong.

Thread Thread
 
cgatian profile image
Chaz Gatian

Enlighten us Jose

Thread Thread
 
webjose profile image
José Pablo Ramírez Vargas

The author changed the example completely now. This new example is OK, although it is a bit longer and has unneeded functions (for the purposes of demonstrating covariance).

Collapse
 
markuszeller profile image
Markus Zeller

console.log(func("True")) //Error: boolean cannot be passed as argument is not correct. "True" is a string, but boolean is declared as acceptable in here function func(param:number|boolean). Comments lie. Am I an liar?

Collapse
 
niharikaa profile image
Niharika Goulikar

Image description
I didn't get you

Collapse
 
markuszeller profile image
Markus Zeller

The string "true" is not a the boolean type true.
typeof("true") !== typeof(true)

Image description

Thread Thread
 
niharikaa profile image
Niharika Goulikar

I know I wanted to show that it we will get error when we pass "True" when we are only supposed to pass either string or number.

Thread Thread
 
markuszeller profile image
Markus Zeller

I think you refer the wrong part. I am talking about 6. Conditional Types.

Quoting:

function func(param:number|boolean){
return param;
}
console.log(func(2)) //Output: 2 will be printed
console.log(func("True")) //Error: boolean cannot be passed as argument
Enter fullscreen mode Exit fullscreen mode

**number **and **boolean **are allowed, but you pass a string. The comment is wrong telling a **boolean **can not be passed. Same for using "True" as string pretending a true boolean is very misleading and terrible wording.

Thread Thread
 
niharikaa profile image
Niharika Goulikar • Edited

Ahhh!Let me fix the comment.
Thanks for reading!

Thread Thread
 
yulia_lantzberg_ profile image
Yulia Lantzberg

@niharikaa you should fix the comment. It is "Error: string cannot be passed as argument. " Boolean is one of the optional parameters in the function. "True" is the string, it is not a boolean. true without quotes and without capital letter is a boolean

Thread Thread
 
markuszeller profile image
Markus Zeller

You're welcome and thanks for the article.

Collapse
 
martygo profile image
Martins Gouveia

Thanks to your article, I was able to understand D.I

Collapse
 
akshaya_goulikar_0d04bc39 profile image
Akshaya Goulikar

Very helpful!Thanks for the article.

Collapse
 
komsenapati profile image
K Om Senapati

Awesome detailed explanation 🔥

Collapse
 
harshika_982e868132d9ddba profile image
Harshika

Amazing article!

Collapse
 
suraj_kumar_79ebbb6e3724f profile image
SuRaj KuMar

Such a Great Article......Thanks for Sharing....!!!!!!

Collapse
 
appasaheb4 profile image
Appasaheb

Great very useful all points.
Thanks for sharing ☺️

Collapse
 
rohan_sharma profile image
Rohan Sharma

Thanks for sharing such a detailed blog!

Collapse
 
rohittcodes profile image
Rohith Singh

great article and great explanation too👏

Collapse
 
dfordp profile image
Dilpreet Grover

Cool!

Collapse
 
jayaramviswanathr profile image
Viswanath R

Great Article!

Collapse
 
nikitimi profile image
Gian Carlo Carranza • Edited

Wouldn't example 3. implemented in the UserRepository class should be:

     class UserRepository implements Repository<User, number | string>
Enter fullscreen mode Exit fullscreen mode

Since you've passed number | string as type in the parameter of getById method?

Although it will be more longer, I think it is more appropriate to stick to the pattern,
Great article btw 😉.

Collapse
 
niharikaa profile image
Niharika Goulikar • Edited

getById(idOrName: number | string): User | undefined, works because it is structurally compatible with the interface. TypeScript ensures that the method can handle number as required by the interface. The additional support for string is treated as extra functionality, not a violation. TypeScript does not strictly enforce that methods must match the interface exactly, as long as they satisfy the required types. This flexibility allows the class to extend functionality while remaining compatible.

Yes, we can adjust it as you suggested for better clarity. However, the provided example is already working perfectly fine.

Collapse
 
thesohailjafri profile image
Sohail SJ | chakraframer.com

HasProperty was cool to know! But in what context I can use it?

Collapse
 
eric_b_67cb420d1a0eddc900 profile image
Eric B • Edited

Here's an example where I had to use it. I was using a component library in Nuxt.js for a table. It took in two paramters; data and columns. The columns parameter was a list of objects with a property label of type string and a property key of type string. The key described which properties to read for that specific column. For example:

type Data = {
    data: {
        name: {
            first: string;
            last: string;
        }
    }
}

columns = [
    {label: "Name", key="data.name.first"} // ok
    {label: "Age", key="data.age"} // error, data.age does not exist
]

<Table :data="somedata: Data" :columns="columns" />
Enter fullscreen mode Exit fullscreen mode

It's a similar problem, but slightly more advanced because you need to create a recursive type as well as do some string literal types in typescripts type system (not javascript).

Collapse
 
thesohailjafri profile image
Sohail SJ | chakraframer.com

My brain hurts but its cool. something new to learn about typescript <3

Collapse
 
chety profile image
Chety

Examples are often too lengthy and can be confusing, particularly those related to generics. The last example, "Dependency Injection," is not specifically a TypeScript concept. I was expecting to see advanced TypeScript concepts, as the title suggests, but it feels more like clickbait.

Collapse
 
helbinrapheal profile image
Helbin Rapheal

It would be interesting to go through some real-world examples or use cases where these advanced TypeScript concepts, like conditional types or dependency injection, have significantly improved the development process or project outcomes.

Collapse
 
imprimph profile image
Info Comment hidden by post author - thread only accessible via permalink
Jaswanth

Man, was preparing for typescript interview today mrng, i asked gpt to give a few examples about generics, it gave the same examples with same parameters, types and explanation

AI content!

Collapse
 
niharikaa profile image
Niharika Goulikar

Thanks for your feedback.
Some examples might be AI-generated, but I customized a few of them for better understanding. I also referred to the official documentation for accuracy.

Collapse
 
z2lai profile image
z2lai

Nice list of features and examples. The infer concept seems helpful but I still don't understand it as there wasn't an explanation, but good enough for me to lookup more on my own. Thanks for sharing!

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

Great. tnx.

Collapse
 
eshimischi profile image
eshimischi

These technics are not "advanced" because all of them just what make Typescript - Typescript. Not the first day.

Collapse
 
niharikaa profile image
Niharika Goulikar

Every programming language has advanced concepts that you come across as you gain more experience. These concepts are, of course, expressed in the language itself, so I'm not sure what you're trying to point out here.

Collapse
 
quan_tran profile image
Quân Trần

something new to learn about typescript <3

Collapse
 
marksantiago02 profile image
Mark Santiago

Good article. thank you

Some comments have been hidden by the post's author - find out more