0
0
Typescriptprogramming~5 mins

Type annotation on variables in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is type annotation on variables in TypeScript?
Type annotation is a way to tell TypeScript what type a variable should hold, like number, string, or boolean. It helps catch mistakes before running the code.
Click to reveal answer
beginner
How do you add a type annotation to a variable in TypeScript?
You write a colon (:) after the variable name, then the type. For example: <code>let age: number;</code> means age can only hold numbers.
Click to reveal answer
beginner
What happens if you assign a wrong type to a variable with type annotation?
TypeScript will show an error before running the program. For example, if <code>let name: string;</code> and you try <code>name = 5;</code>, it will warn you.
Click to reveal answer
beginner
Can you give an example of type annotation with a variable holding a boolean?
Yes! For example: <code>let isOpen: boolean = true;</code> means the variable <code>isOpen</code> can only be true or false.
Click to reveal answer
beginner
Why is type annotation useful when working with variables?
It helps you and the computer understand what kind of data the variable should have. This prevents bugs and makes your code easier to read and maintain.
Click to reveal answer
How do you write a type annotation for a variable named score that holds numbers?
Alet score = number;
Blet score: number;
Clet score: 'number';
Dlet score number;
What will TypeScript do if you assign a string to a variable annotated as a number?
AShow an error before running the code
BAutomatically convert the string to number
CIgnore the type and run anyway
DDelete the variable
Which of these is a valid type annotation for a boolean variable?
Alet isReady: bool;
Blet isReady: yesno;
Clet isReady: Boolean;
Dlet isReady: boolean;
What does this code mean? let name: string = 'Alice';
AVariable <code>name</code> must hold text and starts with 'Alice'
BVariable <code>name</code> can hold any type
CVariable <code>name</code> holds a number
DVariable <code>name</code> is undefined
Why might you want to use type annotations on variables?
ATo make variables change type automatically
BTo make the program run faster
CTo catch mistakes early and make code clearer
DTo hide the variable's value
Explain what type annotation on variables means and how to write it in TypeScript.
Think about how you tell TypeScript what kind of data a variable should hold.
You got /3 concepts.
    Describe why using type annotations on variables is helpful when writing code.
    Consider how knowing the type of data helps both you and the computer.
    You got /3 concepts.