25
loading...
This website collects cookies to deliver better user experience
// STRING
let name: string,
name='sam' // OR name = "sam"
// NUMBER
let age: number
age = 201 //
// BOOLEAN
let isOnline: boolean
// function signature
let sayHello: (person: string) => string
// STRING ARRAY
let names: string[] = ['becker', 'ahmed', 'james']
names = [1, false, 17] // Not Okay
// NUMBER ARRAY
let prices: number[] = [1, 11, 7]
prices = ['shoes'] // Not Okay
// TUPLES
let arr :[number, string, boolean]
arr = [1, 'becker', true] // Okay
arr = [false, 'becker', 1] // Not Okay
interface Car {
wheels: number,
color: string,
plateNumber: string,
manufacturer: string,
model: string
}
// Okay satisfies the contract
let lambo: Car = {
wheels: 4,
color: 'red',
plateNumber: '234RE2',
manufacturer: 'Lamborghini',
model: 'sesto elemento'
}
// Not okay must satisfy the contract
let randCar : Car = {
wheels: '2',
plateNo: 23424,
}
// TYPE ALIAS
type color: = 'red'
// COMBINING WITH UNION TYPES
type carColor = 'red' | 'green' | 'blue' | 'yellow'
// UNION TYPES
let plateNumber: string | number
let lamboColor:carColor = 'red' // Okay
lamboColor = 'purple' // Not Okay
// TYPE THEORY
z: nat
clickZ: nat -> nat
//TYPESCRIPT'S TYPE ANNOTATION
let num: number
let logNum: (num: number) => number;
// When we know the type of a value
let name: string = 'supes'
// When we don't know the type of value a hero will hold
let hero: any
hero = 'superman'
// OR
hero = {name}
// OR
hero = true
// OR
hero = 3
any
and you can work much like you do in JavaScript.//INSTEAD OF
let name: string = 'supes'
//RATHER USE
let job = 'coding'
let age = 20
// TypeScript will auto infer the string type to job
// and number to age
job = 600 // Not okay
age = false // Not okay
any
type.type user = {
name: string,
id: string
}
let sayHello : (obj: user) => string
let sam: user = {
name: 'sam',
id: '1'
}
let superAdmin = {
name: 'super',
id: '11'
}
sayHello = obj:user => return `${obj.name} says hello`;
// VALID
console.log(sayHello(sam)) // sam says hello
// VALID
console.log(sayHello(superAdmin)) // super says hello
type userId = 'user'
type adminId = 'admin'
type user<uid extends string> = {
name: string,
id: uid
}
let sayHello: (obj: user<userId>) => string
let sam:user<userId> = {
name: 'sam',
id: 'user'
}
let superAdmin = {
name: 'super',
id: 'admin'
}
// POSSIBLE
console.log(sayHello(sam)) // sam
// NOT POSSIBLE
conosle.log(sayHello(superAdmin))
// Will show error in IDE
let callPerson: (phoneNo: number) => string
callPerson = (phoneNo) => `calling ${phoneNo}...`
let callKala = callPerson(234804568890); // Okay
let callFrank = callPerson('234804568890') // Not Okay
callKala = 23 // Not Okay coz callKala is a string, type inference
null
or undefined
. An expression that returns either of the two also fits intolet log = () => null
let widened = log()