# npm
npm install typescript --save-dev
# yarn
yarn add typescript --dev
# npm
npx tsc
#yarn
yarn tsc
# npm
npx tsc -w
#yarn
yarn tsc -w
cd ~/Workspace/my-awesome-project
tsc --init
tsconfig.json filemessage.toLowerCase()
message()
const message = "Hello World!"
message.toLowerCase() // it works
message() // error → This expression is not callable.
messagestring, number and booleanstring[], number[] or Array<number>any can be used - TS use this if the compiler cannot infer the contextvoid for callbacks or function returnnull and undefined to signal absent or uninitialized valuenumber | string'left' | 'right' | 'center'const myName:string = "John"function greet(name: string) { … }function getName(): string { … }function print(point: { x:number, y:number }) { … }? for optional properties → function printName(first: string; last?: string) { … }// using the `as` keyword
const logo = document.getElementById('logo') as HTMLImageElement
// using angle-bracket syntax
const logo = <HTMLImageElement>document.getElementById('logo')
! says TS that the value isn't null or undefinedtype alias → a name for any typetype ID = number | string
type Point = {
x: number
y: number
}
function printCoords(id: ID, pt: Point) {
if (typeof id === 'string') {
console.log(id.toUpperCase())
} else {
console.log(id)
}
console.log(pt.x, pt.y)
}
…
interface Point = {
x: number
y: number
}
function printCoords(pt: Point) {
console.log(pt.x, pt.y)
}
| Aspect | Type | Interface |
|---|---|---|
| Can describe functions | ✅ | ✅ |
| Can describe constructors | ✅ | ✅ |
| Can describe tuples | ✅ | ✅ |
| Interfaces can extend it | ⚠️ | ✅ |
| Classes can extend it | 🚫 | ✅ |
Classes can implement it (implements) |
⚠️ | ✅ |
| Can intersect another one of its kind | ✅ | ⚠️ |
| Can create a union with another one of its kind | ✅ | 🚫 |
| Can be used to create mapped types | ✅ | 🚫 |
| Can be mapped over with mapped types | ✅ | ✅ |
| Expands in error messages and logs | ✅ | 🚫 |
| Can be augmented | 🚫 | ✅ |
| Can be recursive | ⚠️ | ✅ |
⚠️ In some cases
readonly fields prevents assignments outside of the constructorextends keywordsuper to access base class methodsimplementsprivate, public or protectedconstructor(public foo: string)static membersconst foo = class<T> { … }abstractfunction identity(arg: number): number {
return arg;
}
any typefunction identity(arg: any): any {
return arg;
}
any typefunction identity<Type>(arg: Type): Type {
return arg;
}
let out1 = identity<string>('hello')
let out2 = identity(42)
let out3 = identity<MyCustomType>(value)
identity<T, U>(a: T, b: U): T { … }