溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

typescript 基本類型 | Symbol | 接口| 函數(shù)| 泛型-- 學習筆記二

發(fā)布時間:2020-06-21 21:05:57 來源:網(wǎng)絡(luò) 閱讀:528 作者:295631788 欄目:web開發(fā)

typescript 基本類型 | Symbol | 接口| 函數(shù) -- 學習筆記二

基本類型


let bool:boolean = false
let num:number = 123
let str:string
str = "abc"
str = `數(shù)值是${num}`

let arr1: number[] = [1,2,3]
let arr2: Array<number | string > = [1,2,3]
let arr3: (string | number)[] = ['a',2,'c']

let tuple: [string,number,boolean] = ['a',2,true]

// 枚舉
enum Roles {
    SUPER_ADMIN = 0,
    ADMIN,
    USER
}

// any類型
let value: any
value = "123"
const arr4: any[]=[1,'b']

// void類型

let v: void = undefined

const consoleText=(text: string): void =>{
    console.log(text)
}
consoleText("abc")

// null  undefined
let u: undefined = undefined
let n: null  = null

// never類型
const errorFunc = (message: string): never =>{
    throw new Error(message)
}
const infiniterFunc =():never =>{
    while(true){}
}
let neverVariable = (()=>{
    while(true){}
})

// object
let obj:object = {
    name : 'hequan',
}

// 類型斷言
const  getLength = (target:string | number) : number =>{
    if ((<string>target).length || (target as string).length === 0){
        return (<string>target).length
    }else{
        return target.toString().length
    }
}

Symbol

const s = Symbol("name") //唯一的值

const info ={
[s]:'hequan'
}
info[s]='123'
Object.getOwnPropertySymbols(info)
Reflect.ownKeys(info)

const s1 = Symbol.for('he') // 全局注冊 先查找是否存在,沒有再創(chuàng)建
Symbol.keyFor(s1) // 只查找 for創(chuàng)建的

接口

"tslint.autoFixOnSave": true,

tslint  --init

{
    "root": false,
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "quotemark": [false],
        "semicolon": [false],
        "interface-name": [true, "never-prefix"],
        "object-literal-sort-keys": [false]
    },
    "rulesDirectory": []
}

interface NameInfo {
    firstName?: string, // ? 可選
    lastName: string,  // readonly lastName: string,
    [prop: string]: any
}

const getFullName = ({ firstName, lastName}: NameInfo): string => {
    return `${firstName}${lastName}`
}

getFullName({
    firstName: "he",
    lastName: "quan",
    other: 1,
} as NameInfo)

interface RoleDic {
    [id: string]: string,
}

const role: RoleDic = {
    0: 'super_admin',
    1: 'admin',
}

interface User extends NameInfo {
    age: number,
}

const user1: User = {
    firstName: "t",
    lastName: "o",
    age: 11,
}

函數(shù)

let add: (x: number, y: number) => number

add = (arg1: 1, arg2: 2): number => arg1 + arg2

type Add = (x: number, y: number, z?: any) => number  // 類型別名

let addFunction = (x: number, y = 2) => x + y

let arr10 = [1, 2, 3]
let arr11 = [...arr10]

// 重載
function handleData(x: string): string[]
function handleData(x: number): number[]
function handleData(x: any): any {
    if (typeof x === "string") {
        return x.split('')
    } else {
        return x.toString().split('').map((item) => Number(item))
    }
}

泛型

const getArry = <T>(value: T, times: number = 5): T[] => {
    return new Array(times).fill(value)
}

getArry<number>(1234, 4).map((item) => item.toFixed())

const getArray1 = <T, U>(param1: T, param2: U, times: number): Array<[T, U]> => {
    return new Array(times).fill([param1, param2])
}
getArray1<number, string>(1, 'a', 3).forEach((item) => {
    console.log(item[0])
    console.log(item[1])
})

interface ValueWithLength {
    length: number
}

const getArray2 = <T extends ValueWithLength>(arg: T, times): T[] => {
    return new Array(times).fill(arg)
}
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI