0
0
Typescriptprogramming~5 mins

Type alias for objects in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a type alias in TypeScript?
A type alias is a name given to a specific type, including object shapes, so you can reuse it easily in your code.
Click to reveal answer
beginner
How do you define a type alias for an object with properties name (string) and age (number)?
You write:
type Person = { name: string; age: number; };
Click to reveal answer
intermediate
Can a type alias describe optional properties in an object? How?
Yes, by adding a question mark after the property name. Example:
type Person = { name: string; age?: number; };
Here, age is optional.
Click to reveal answer
beginner
What happens if you try to assign an object missing a required property to a variable typed with a type alias?
TypeScript will show an error because the object does not match the required shape defined by the type alias.
Click to reveal answer
intermediate
Can type aliases be used to describe nested objects? Give an example.
Yes. Example:
type Address = { city: string; zip: string; };
type Person = { name: string; address: Address; };
Click to reveal answer
How do you create a type alias for an object with a string property 'title' and a number property 'pages'?
Ainterface Book = { title: string; pages: number; };
Btype Book = (title: string, pages: number);
Ctype Book = { title: string; pages: number; };
Dlet Book = { title: string; pages: number; };
Which symbol marks a property as optional in a TypeScript type alias?
A?
B!
C*
D#
What will TypeScript do if you assign an object missing a required property to a variable typed with a type alias?
AConvert the object to any type
BIgnore the missing property
CAutomatically add the missing property
DShow an error
Can type aliases be used to describe nested objects?
AYes
BNo
COnly with interfaces
DOnly with classes
Which keyword is used to create a type alias in TypeScript?
Ainterface
Btype
Calias
Dclass
Explain how to create a type alias for an object with both required and optional properties.
Think about how to mark properties optional in the object.
You got /4 concepts.
    Describe how nested objects can be represented using type aliases in TypeScript.
    Consider defining one type alias inside another.
    You got /3 concepts.