Special TypeScript Types: any and unknown Types Flashcards

1
Q

What’s bad about the any type?

A

It removes the Type Checker guarantees entirely. You’re essentially running JavaScript. You might as well just use JS as you’re getting none of the benefits.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s one place that ‘any’ might be helpful?

A

Network calls, since you can’t know what type the network call will return without adding an annotation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What can you do if you do need to use the any type, such as with network calls?

A

You can add an annotation to make it clear what’s happening here. In the code pictured, TypeScript will take that annotation and use it as the type of the variable. When you put any into the variable, it turns that ‘any’ type into whatever type was used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the unknown type?

A

It can represent any type, but it gives us limitations on what we can do with that type, so that we can maintain type safety.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why is this code throwing an error?

A

Because if a variable’s type is unknown, then you’re limited from doing non-type-safe things with it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How is the unknown type helpful, since we can’t do anything with it?

A

We can use Type Narrowing to convince TypeScript that it’s actually a more specific type. This involves runtime checks that prove a value is or is not a specific type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is this an example of?

A

Type Narrowing - we use the typeOf operator to prove that our type is a number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Type Narrowing?

A

Using a run-time check to ensure that a variable is of a certain type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Should we use any or unknown?

A

any gives the most flexibility, but with no type safety. Avoid unless absolutely necessary.

unknown gives us zero flexibility, but it does maintain the type safety guarantee and encourages you as a developer to then use Type Narrowing to determine a more accurate type.

So, prefer unknown with type narrowing in all cases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly