Typescript 1 Flashcards
What is a statically typed language?
It’s type-checked and compiled before you can run it.
In Typescript, can you change the type of a variable partway through a program?
No
What does Typescript need to be compiled into before it’s run in a browser?
TypeScript needs to be compiled into JavaScript before it can be run in a browser.
When do you receive an error if your code is not correctly typed in Typescript?
At compile time.
What are the 2 ways you can declare a type in Typescript?
Explicit type annotations:
let a: number = 1 // a is a number
let b: string = ‘hello’ // b is a string
let c: boolean[] = [true, false] // c is an array of
Inferred types:
let a = 1 // a is a number
let b = ‘hello’ // b is a string
let c = [true, false] // c is an array of Booleans
What is the command for the Typescript compiler?
$> tsc hello_world.ts
What is the Any type?
The any type is a catch-all type:
let a: any = 123
let b: any = [‘danger’]
let c = a + b // Value is ‘123danger’
Use any sparingly. Overuse can remove the benefits of type-checking
What is the Unknown type?
The unknown type is a safer counterpart to any.
TypeScript will never infer something as unknown. You have to explicitly annotate it:
let a: unknown = 30;
It only supports a limited set of operations. You can just compare
unknown values (using ==, ===, !=, !==)
What is a Literal type?
Literal types allow you to specify the exact value a variable must have.
let e: true = true, e can only ever be true.
let f: 26.218 = 26.218
What is a symbol type?
TypeScript has a symbol type which is unique and immutable data type and is often used to identify object properties.
let a = Symbol('a') // symbol
How do you define an object in Typescript?
let a: object = {
b: ‘x’
}
console.log(a[‘b’])
let c: { d : string } = {
d: ‘y’
}
console.log(c.d)
The type {d: string} means an object with a string property d
How are object types enforced in Typescript?
TypeScript enforces the object shape defined by the type.
let a: {b: number}
a = {} // Error TS2741: Property ‘b’ is missing in type ‘{}’
// but required in type ‘{b: number}’.
a = {
b: 1,
c: 2 // Error TS2322: Type ‘{b: number; c: number}’ is not
} // assignable to type ‘{b: number}’
How to define an optional value in Typescript?
c? means c is an optional property.
let a: {
b: number
c?: string
[key: number]: boolean
}
How to define a read only property in Typescript?
TypeScript allows properties to be marked as ‘readonly‘ which means
they can’t be reassigned after initialisation.
let user: {
readonly firstName: string
} = {
firstName: ‘abby’
}
How to declare Type Aliases in Typescript?
You can create new names for types using type aliases:
type Age = number
type Person = {
name: string
age: Age
}
let age: Age = 55
let driver: Person = {
name: ‘James May’,
age: age
}