Basic example of typescript

Keywords: Programming Java

ts, as a js with added type, is similar to java at first, but later I found that there are many differences

 

fib with type example

function fib(n: number): number {
    return n < 2 ? n : fib(n - 1) + fib(n - 2)
}

// 0,1,1,2,3,5,8,13,21,34
console.log([...Array(10)].map((_, k) => fib(k)).join(','))

 

When assigning literal value, there can be redundant attributes in the variable, but not literal value


type Stu = {
    name: String;
    age: Number
}

function f(s: Stu) {
    console.log(s.name, s.age)
}

f({
    name: 'a',
    age: 2,
    score: 60  // Error reporting, more than attributes
})

let s = {
    name: 'a',
    age: 2,
    score: 60
}

f(s) // Can be called successfully

 

 

Closure counter


interface Counter {
    (): number

    count: number
}

function getCounter(): Counter {
    const c: Counter = (): number => c.count++
    c.count = 0
    return c
}


let c: Counter = getCounter()
c()
console.log(c.count)
c()
console.log(c.count)
c()
console.log(c.count)

One detail is that if you use let, you will report an error. You must use const

 

 

generic paradigm


function getM<T>(size: number, val: T): T[] {
    return Array(size).fill(val)
}

let m = getM(3, 0)
console.log(m)

 

 

Generic constraints

function getProp<T, K extends keyof T>(obj: T, k: K) {
    return obj[k]
}

let obj = {
    's': 'abc',
    1: []
}
getProp(obj, 's')
getProp(obj, 1)

 

Boolean objects are always converted to true when they operate on Boolean values

let a = new Boolean(true)
let b = new Boolean(false)
let c = Boolean(true)
let d = Boolean(false)

console.log(a && b) // [Boolean: false]
console.log(c && d) // false
console.log(b && true) // true
console.log(d && true) // false

 

The main difference between the common built-in object and the basic wrapper type is the life cycle of the object. Instances of reference types created with the new operator are always saved in memory before the execution flow leaves the current scope. The automatically created basic wrapper type objects only exist at the execution moment of a line of code, and are immediately destroyed. This means that we can no longer add properties and methods to the base wrapper type values at run time.

let s = "abc"
s.name = 'a'
console.log(s.name) // undefined

Posted by abgoosht on Mon, 01 Jun 2020 08:47:43 -0700