Similar presentations:
TypeScript In-Depth: Types Basics
1.
TypeScript In-Depth:Types Basics
CONFIDENTIAL
1
2.
OutlineCONFIDENTIAL
1
Declaring Variables with var, let and const
2
Basic Types
3
Type Assertions
4
Intersection and Union Types
5
Advanced Features of Types
6
Type Inference and Type Annotation
7
Type Definitions
2
3.
VAR, LET AND CONSTCONFIDENTIAL
3
4.
Declaring Variables with var, let and constvar
let, const
• Globally available in the function
in which it is declared
• Only available in the block in which
it is declared
• “Hoisted” to the top of the
function
• Not “hoisted” to the top of the
block
• Variable name may be declared a
second time in the same function
• Variable name may only be
declared once per block
const => let => var
CONFIDENTIAL
4
5.
BASIC TYPESCONFIDENTIAL
5
6.
Basic TypesBoolean
Enum
Object
Number
Tuple
Null
String
Any
Undefined
Array
Void
Never
ReadonlyArray
BigInt
CONFIDENTIAL
v3.2
Unknown
v3.0
6
7.
Boolean, Number Typeslet isDone: boolean = false;
let
let
let
let
decimal: number = 6;
hex: number = 0xf00d;
binary: number = 0b1010;
octal: number = 0o744;
// Numeric separators, since 2.7
const million = 1_000_000;
const phone = 555_73_22;
const bytes = 0xFF_0C_00_FF;
const word = 0b1100_0011_1101_0001;
CONFIDENTIAL
//
//
//
//
1000000
5557322
4278976767
50129
7
8.
String Typeslet color: string = "blue";
color = 'red';
let name: string = `Vitaliy`;
let sentence: string = `Hello, ${ name }`;
CONFIDENTIAL
8
9.
Arraylet strArray1: string[] = ['here', 'are', 'strings'];
let strArray2: Array<string> = ['more', 'strings', 'here'];
let anyArray: any[] = [42, true, 'string’];
let numStrArray: Array<number | string> = [42, 'string'];
• Accessed and used much like JavaScript
• Can be declared two different ways
• Declared as an array of “any” to store any type in the same array
CONFIDENTIAL
9
10.
ReadonlyArraylet num: Array<number> = [1, 2, 3, 4, 5];
let roNum: ReadonlyArray<number> = [...num];
roNum[0] = 20;
// error
roNum.push(5);
// error
roNum.length = 100;
// error
num = roNum;
// error
num = roNum as Array<number>;
// ok
• The same as Array<T> with all mutating methods removed
CONFIDENTIAL
10
11.
Tuplelet myTuple: [number, string] = [25, 'string'];
let firstElement = myTuple[0];
// 25
let secondElement = myTuple[1];
// string
myTuple[0] = 100;
// [number, string]
myTuple[1] = 'this works';
// [number, string]
myTuple[0] = true;
// Error
myTuple = [25, 'string', 100, 'this works']; // Error since 2.7
CONFIDENTIAL
11
12.
Optional and Rest Elements in Tuplelet myTuple: [number, string?, boolean?];
myTuple = [1, 'Anna', true];
// ok
myTuple = [2, 'Boris’];
// ok
myTuple = [3];
// ok
let otuple: [number, ...string[]];
otuple = [1, 'Anna'];
otuple = [2, 'Anna', 'Boris'];
CONFIDENTIAL
12
13.
Enum (Numbers)enum Category { JavaScript, CSS, HTML } // 0, 1, 2
enum Category { JavaScript = 1, CSS, HTML } // 1, 2, 3
enum Category { JavaScript = 5, CSS = 8, HTML = 9 } // 5, 8, 9
let favoriteCategory: Category = Category.JavaScript;
console.log(favoriteCategory); // 5
let categoryString = Category[favoriteCategory];
console.log(categoryString); // JavaScript
CONFIDENTIAL
13
14.
Enum (Strings)enum Category { A = 'JavaScript', B = 'CSS', C = 'HTML' }
let favoriteCategory: Category = Category.A;
console.log(favoriteCategory); // JavaScript
CONFIDENTIAL
14
15.
Anylet notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
CONFIDENTIAL
15
16.
Voidfunction warnUser(): void {
alert("This is my warning message");
}
// only undefined or null
let unusable: void = undefined;
unusable = null;
CONFIDENTIAL
16
17.
BigIntlet a: bigint = BigInt(100);
let b: bigint = 100n; // doesn’t work in v3.2.2?
let c: number = 100;
c = a;
// error: Type 'bigint' is not assignable to type 'number'.
b = c;
// error: Type 'number' is not assignable to type 'bigint’.
b = a + BigInt(c); // 200n
typeof b; // 'bigint'
CONFIDENTIAL
17
18.
Objectfunction create(o: object | null): void {…};
create({ prop: 0 });
// OK
create(null);
// OK
create(42);
// Error
create("string");
// Error
create(false);
// Error
create(undefined);
// Error
CONFIDENTIAL
18
19.
Undefined and Null// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
CONFIDENTIAL
19
20.
Never// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) { }
}
CONFIDENTIAL
20
21.
Unknown// Only equality operators
// are allowed with unknown
let x: unknown;
x === 5;
// ok
x !== 10; // ok
// No property accesses, element
// accesses, or function calls
x.f;
// Error
x[5];
// Error
x();
// Error
new x();
// Error
CONFIDENTIAL
// Anything is assignable to unknown
x = 123;
x = "hello";
x = [1, 2, 3];
// unknown assignable only to itself
// and any
let v1: any = x;
let v2: unknown = x;
// Functions with unknown return
// type don't need return expressions
function f(): unknown {
}
21
22.
TYPE ASSERTIONSCONFIDENTIAL
22
23.
Type Assertions// "angle-bracket" syntax
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// as-syntax
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
CONFIDENTIAL
23
24.
INTERSECTION AND UNION TYPESCONFIDENTIAL
24
25.
Intersection Typesfunction f(person: Person, account: Account): Person & Account {
let result: Person & Account;
result = {…person, …account};
return result;
}
CONFIDENTIAL
25
26.
Union Types: Primitivesfunction f(a: string | number, b: string | number): string | number {
// body of the function f
}
CONFIDENTIAL
26
27.
Union and --strictNullChecks Compiler Option// tsconfig.json
"strictNullChecks": true
let basicString: string;
basicSctring = null;
basicString = undefined;
// error
// error
let nullableString: string | null;
nullableString = null;
// ok
nullableString = undefined; // error
let anyString: string | null | undefined;
anyString = null;
// ok
anyString = undefined;
// ok
CONFIDENTIAL
27
28.
Union and ! operatorlet myElement: HTMLElement | null = document.getElementById("div");
myElement.innerText = "Some text";
// Error: Object is possibly "null“
myElement!.innerText = "Some text";
// Ok, myElement is not null/undefined
CONFIDENTIAL
28
29.
Union Types: Objectsclass Bird { fly(){} layEggs(){} }
class Fish { swim(){} layEggs(){} }
function getPet(): Bird | Fish {
return new Bird();
}
const pet = getPet();
pet.layEggs();
// ok
pet.fly();
// error
(<Bird>pet).fly() // ok
CONFIDENTIAL
29
30.
User-Defined Type Guardsfunction isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
if (isFish(pet)) {
pet.swim();
// here pet is Fish
} else {
pet.fly();
// here pet is Bird
}
CONFIDENTIAL
30
31.
ADVANCED FEATURES OF TYPESCONFIDENTIAL
31
32.
Type Aliasestype Name = string;
type Runner = () => string;
type NameOrRunner = Name | Runner;
CONFIDENTIAL
32
33.
String Literal Typetype Easing = "ease-in" | "ease-out" | "ease-in-out";
function animate(easing: Easing) {
// …
}
animate("ease-in"); // ok
animate("uneasy");
CONFIDENTIAL
// error
33
34.
keyof (called “key query types”)const id = Symbol('id');
// unique symbol | "name" | "age" |
interface Person {
"location"
[id]: number;
// support symbol v2.9
name: string;
type K = keyof Person;
age: number;
location: string;
function f(k: K) {
}
console.log(p[k]);
const p: Person = {
}
[id]: 1,
name: "Anna",
f("name");
// ok
age: 16,
f("firstName");
// error
location: "Kiev"
};
CONFIDENTIAL
34
35.
Partialconst id = Symbol('id');
interface Person {
[id]: number;
name: string;
age: number;
location: string;
}
// Error
const p1: Person = {
name: "Anna"
};
type PartialPerson = Partial<Person>;
// equivalent to
interface PartialPerson {
[id]?: number;
name?: string;
age?: number;
location?: string;
}
// OK
const p2: Partial<Person> = {
name: "Boris"
};
// support symbol properties since v2.9
CONFIDENTIAL
35
36.
Partial and Readonlyconst id = Symbol('id');
const p3: Partial<Readonly<Person>> = {
interface Person {
name: "Anna"
[id]: number;
};
name: string;
// Error
age: number;
p3.name = "Clara";
location: string;
}
// support symbol properties since v2.9
CONFIDENTIAL
36
37.
TYPE INFERENCE AND TYPE ANNOTATIONCONFIDENTIAL
37
38.
Type Inferencelet firstString = 'this a string';
firstString = 42; // error
function returnNmber() {
return 42;
}
let anotherString = 'this is another string';
anotherString = returnNumber(); // error
CONFIDENTIAL
38
39.
Type Annotationslet firstString: string = 'this a string';
firstString = 42; // error
function returnNmber(): number {
return 42;
}
let anotherString: string = 'this is another string';
anotherString = returnNumber(); // error
CONFIDENTIAL
39
40.
Practice 01-02: Types• Perform actions according to Task 01, Task 02 from Practice document
CONFIDENTIAL
40
41.
WHAT ARE TYPEDEFINITIONS?
CONFIDENTIAL
41
42.
What are Type Definitions?1. Files with type information for a
library
2. Contain no implementation details
3. Primarily used as a TypeScript
wrapper for JavaScript libraries
4. Design-time tool for type-checking
and editor support
5. File names end with .d.ts
CONFIDENTIAL
42
43.
Download and Installnpm install --save @types/lodash
Getting type declarations in TypeScript 2.0 and above requires no tools apart from npm.
For the most part, type declaration packages should always have the same name as the
package name on npm, but prefixed with @types/
If you need, you can check out http://microsoft.github.io/TypeSearch/ to find the package
for your favorite library
CONFIDENTIAL
43
44.
SummaryCONFIDENTIAL
1
Declaring Variables with var, let and const
2
Basic Types
3
Type Assertions
4
Intersection and Union Types
5
Advanced Features of Types
6
Type Inference and Type Annotation
7
Type Definitions
44