溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue3中Typescript的基本使用方法有哪些

發(fā)布時(shí)間:2022-02-24 16:02:10 來源:億速云 閱讀:407 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Vue3中Typescript的基本使用方法有哪些”,在日常操作中,相信很多人在Vue3中Typescript的基本使用方法有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”Vue3中Typescript的基本使用方法有哪些”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

變量申明

基本類型

let isDone: boolean = false
let num: number = 1
let str: string = 'vue3js.cn'
let arr: number[] = [1, 2, 3] 
let arr2: Array<number> = [1, 2, 3] // 泛型數(shù)組
let obj: Object = {}
let u: undefined = undefined;
let n: null = null;

類型補(bǔ)充

  • 枚舉 Enum

使用枚舉類型可以為一組數(shù)值賦予友好的名字

enum LogLevel {
  info = 'info',
  warn = 'warn',
  error = 'error',
}
  • 元組 Tuple

允許數(shù)組各元素的類型不必相同。比如,你可以定義一對(duì)值分別為 string和number類型的元組

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error
  • 任意值 Any

表示任意類型,通常用于不確定內(nèi)容的類型,比如來自用戶輸入或第三方代碼庫

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
  • 空值 Void

與 any 相反,通常用于函數(shù),表示沒有返回值

function warnUser(): void {
    console.log("This is my warning message");
}
  • 接口 interface

類型契約,跟我們平常調(diào)服務(wù)端接口要先定義字段一個(gè)理

如下例子 point 跟 Point 類型必須一致,多一個(gè)少一個(gè)也是不被允許的

interface Point {
    x: number
    y: number
    z?: number
    readonly l: number
}
const point: Point = { x: 10, y: 20, z: 30, l: 40 }
const point2: Point = { x: '10', y: 20, z: 30, l: 40 } // Error 
const point3: Point = { x: 10, y: 20, z: 30 } // Error 
const point4: Point = { x: 10, y: 20, z: 30, l: 40, m: 50 } // Error

可選與只讀 ? 表示可選參, readonly 表示只讀

const point5: Point = { x: 10, y: 20, l: 40 } // 正常
point5.l = 50 // error

函數(shù)參數(shù)類型與返回值類型

function sum(a: number, b: number): number {
    return a + b
}

配合 interface 使用

interface Point {
    x: number
    y: number
}


function sum({ x,  y}: Point): number {
    return x + y
}


sum({x:1, y:2}) // 3

泛型

泛型的意義在于函數(shù)的重用性,設(shè)計(jì)原則希望組件不僅能夠支持當(dāng)前的數(shù)據(jù)類型,同時(shí)也能支持未來的數(shù)據(jù)類型

  • 比如

根據(jù)業(yè)務(wù)最初的設(shè)計(jì)函數(shù) identity 入?yún)?code>String

function identity(arg: String){
 return arg
}
console.log(identity('100'))

業(yè)務(wù)迭代過程參數(shù)需要支持 Number

function identity(arg: String){
 return arg
}
console.log(identity(100)) // Argument of type '100' is not assignable to parameter of type 'String'.

為什么不用any呢?

使用 any 會(huì)丟失掉一些信息,我們無法確定返回值是什么類型 泛型可以保證入?yún)⒏祷刂凳窍嗤愋偷模且环N特殊的變量,只用于表示類型而不是值

語法 <T>(arg:T):T 其中T為自定義變量

const hello : string = "Hello vue!"
function say<T>(arg: T): T {
    return arg;
}
console.log(say(hello)) // Hello vue!

泛型約束

我們使用同樣的例子,加了一個(gè)console,但是很不幸運(yùn),報(bào)錯(cuò)了,因?yàn)榉盒蜔o法保證每種類型都有.length 屬性

const hello : string = "Hello vue!"
function say<T>(arg: T): T {
 console.log(arg.length) // Property 'length' does not exist on type 'T'.
    return arg;
}
console.log(say(hello)) // Hello vue!

從這里我們也又看出來一個(gè)跟any不同的地方,如果我們想要在約束層面上就結(jié)束戰(zhàn)斗,我們需要定義一個(gè)接口來描述約束條件

interface Lengthwise {
    length: number;
}


function say<T extends Lengthwise>(arg: T): T {
 console.log(arg.length)
    return arg;
}
console.log(say(1))  // Argument of type '1' is not assignable to parameter of type 'Lengthwise'.
console.log(say({value: 'hello vue!', length: 10})) // { value: 'hello vue!', length: 10 }

交叉類型

交叉類型(Intersection Types),將多個(gè)類型合并為一個(gè)類型

interface foo {
    x: number
}
interface bar {
    b: number
}
type intersection = foo & bar
const result: intersection = {
    x: 10,
    b: 20
}
const result1: intersection = {
    x: 10
}  // error

聯(lián)合類型

交叉類型(Union Types),表示一個(gè)值可以是幾種類型之一。我們用豎線 | 分隔每個(gè)類型,所以 number | string | boolean表示一個(gè)值可以是 number, string,或 boolean

type arg = string | number | boolean
const foo = (arg: arg):any =>{ 
    console.log(arg)
}
foo(1)
foo('2')
foo(true)

函數(shù)重載

函數(shù)重載(Function Overloading), 允許創(chuàng)建數(shù)項(xiàng)名稱相同但輸入輸出類型或個(gè)數(shù)不同的子程序,可以簡單理解為一個(gè)函數(shù)可以執(zhí)行多項(xiàng)任務(wù)的能力

例我們有一個(gè)add函數(shù),它可以接收string類型的參數(shù)進(jìn)行拼接,也可以接收number類型的參數(shù)進(jìn)行相加

function add (arg1: string, arg2: string): string
function add (arg1: number, arg2: number): number


// 實(shí)現(xiàn)
function add <T,U>(arg1: T, arg2: U) {
  // 在實(shí)現(xiàn)上我們要注意嚴(yán)格判斷兩個(gè)參數(shù)的類型是否相等,而不能簡單的寫一個(gè) arg1 + arg2
  if (typeof arg1 === 'string' && typeof arg2 === 'string') {
    return arg1 + arg2
  } else if (typeof arg1 === 'number' && typeof arg2 === 'number') {
    return arg1 + arg2
  }
}


add(1, 2) // 3
add('1','2') //'12'

總結(jié)

通過本篇文章,相信大家對(duì)Typescript不會(huì)再感到陌生了

下面我們來看看在Vue源碼Typescript是如何書寫的,這里我們以defineComponent函數(shù)為例,大家可以通過這個(gè)實(shí)例,再結(jié)合文章的內(nèi)容,去理解,加深Typescript的認(rèn)識(shí)

// overload 1: direct setup function
export function defineComponent<Props, RawBindings = object>(
  setup: (
    props: Readonly<Props>,
    ctx: SetupContext
  ) => RawBindings | RenderFunction
): {
  new (): ComponentPublicInstance<
    Props,
    RawBindings,
    {},
    {},
    {},
    // public props
    VNodeProps & Props
  >
} & FunctionalComponent<Props>


// defineComponent一共有四個(gè)重載,這里省略三個(gè)


// implementation, close to no-op
export function defineComponent(options: unknown) {
  return isFunction(options) ? { setup: options } : options
}

到此,關(guān)于“Vue3中Typescript的基本使用方法有哪些”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

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

AI