TypeScript Crashcourse
2 Maret 2020
Basic Typing
There are 3 basic types in TypeScript
var isDone: boolean = false;
let lines: number = 69;
const name: string = 'Jajang';But you can omit the type annotation if the variables are derived from explicit literals
var isDone = false;
let lines = 69;
const name = 'Jajang';When it's impossible to know, there is the any type
let notSure: any = 4;
notSure = 'maybe a string instead';
notSure = false; // okay, definitely a booleanUse const keyword for constants
const numLivesForCat = 9;
numLivesForCat = 1; // ErrorFor collections, there are typed arrays and generic arrays
let list: number[] = [1, 2, 3];
// Or, using the generic array type
let list: Array<number> = [1, 2, 3];For enumerations
Lastly, void is used in the special case of a function returning nothing.
Functions
Functions are first class citizens, support the lambda 'fat arrow' syntax and use type inference.
The following are equivalent, the same signature will be inferred by the compiler, and same JavaScript will be emitted
Regular function
Return type inferred
'Fat arrow' syntax
'Fat arrow' syntax with return type inferred
'Fat arrow' syntax with return type inferred, braceless means no return keyword needed.
var, let, and const
var, let, and constDeclaring a variable using the above keywords:
Both type and initial value.
Without type, but with an initial value.
Only the type.
Without type and initial value.
Variable Scoping
var is Function Scoped
var is Function Scopedlet and const are Block Scoped
let and const are Block ScopedInterfaces
Interfaces are structural, anything that has the properties is compliant with the interface.
Object that implements the Person interface can be treated as a Person since it has the name and move properties
Object below is not a person because age is not a number and there is no move function.
Interfaces can also describe a function type
Only the parameters' types are important, names are not important.
Classes
Class members are public by default
Classes can be explicitly marked as implementing an interface. Any missing properties will then cause an error at compile-time.
Class inheritance
Generics
Classes
Interfaces
And functions
Template strings
Template Strings: strings that use backticks (`).
String Interpolation with Template Strings
Multiline Strings with Template Strings
Iterators
for..ofstatement. Iterate over the list of values on the object being iterated.
for..instatement. Iterate over the list of keys on the object being iterated.
Higher order functions
More Types
Union Type (
|)
Intersection Types (
&)
Last updated
Was this helpful?