一文了解TypeScript資料型別
阿新 • • 發佈:2021-07-07
目錄
- 基礎型別
- any型別
- 陣列
- 元組
- Interface
- 函式
- 型別自推
- 聯合型別(二選一甚至多選一)
- class
- 列舉
基礎型別
ts中支援更多的型別
let age: number = 10 // Number let firstName: string = '涼宸' // String let lastName: string = '涼宸' // String let isMary: boolean = true // boolean let unde: undefined = undefined // undefined let nu: null = null // null
undefined
和 null
可以作為值賦值給其他型別,因為這兩個可以看作其他型別的子型別
賦值的時候一定要根據定義的資料型別做賦值,否則會有如下提示錯誤
- 宣告變數時,型別與值不符
- 為變數重新賦值時,型別與值不符
any型別
有的時候我們無法確定變數型別,我們可以將其指定型別為any
當我們賦值給其any型別後,可以為其賦任意值,且不會報錯
let isAny:any='任意型別any' isAny=520 isAny=true isAny=null
但是為了避免型別不明確,我們還是儘量少使用any
any 型別的特點
- 允許賦值為任意型別
- 可以訪問任意屬性和方法
let userName: any = '涼宸'; // 可以訪問任意屬性 console.log(userName.name); console.log(userName.name.firstName); // 可以呼叫任意方法 userName.setName('David'); userName.setName('David').sayHello(); userName.name.setFirstName('David');
陣列
我們可以指定陣列內元素型別
let ages: number[] = [5,20,13,14] let names: string[] = ['涼宸','路飛','明世隱','李楊勇']
類陣列:
類陣列是不會擁有陣列擁有的方法,tsc能夠自動識別兩者
let arguments=[555,555,55] function lei(){ let arr:number=arguments }
元組
基本類似於陣列,但是型別可以是多種
let arr:[number,string,boolean]=[520,'涼宸',true]
我們在賦值時一定要根據型別順序填寫
元素能多不能少
let arr:[number,true] arr.push('b') // 可以 arr.push(4) // 可以 arr.push(true) // 可以 console.log(arr)
let arr:[number,string]=[520,'涼宸'] arr.push('b') // 可以 arr.push(4) // 可以 arr.push(true) // 不可以 console.log(arr)
Interface
- 介面可以理解為綱領、比較抽象,其中不會規定的具體的行為,也就是說介面中,我們只定義有屬 性,哪些方法以及屬性的型別,方法的抽象,不會為屬性賦值,也不會定義方法的實現
- 類的話一般屬性要賦值,方法也要有實現
- Interface 的宣告像 class,成員更像字面量物件,而不是 class
作用:
- 對物件的形狀(shape)進行描述
- Duck Typing(鴨子型別)
interface Point{ userName:string|number password:number } // 此時執行tsc不會解析出相應的程式碼,因為此型別是ts特有的,只是表示約束
interface Point{ userName:string|number password:number } let value:Point={ userName:'[email protected]',password:123456 } let val:Point={ userName:55555,password:123456 } // 此時兩種都符合,在執行tsc // 只是出現如下程式碼,沒有任何約束js var value = { userName: '[email protected]',password: 123456 }; var val = { userName: 55555,password: 123456 };
可選屬性 ?
建立 IPerson 介面型別變數時,介面中宣告的屬性,變數賦值時也必須有,否則就會報錯
但我們可以設定某個屬性為可選屬性,在建立變數時,就可以選擇賦值
interface Point{ userName:string|number password:number,email?:string } let value:Point={ userName:'[email protected]',password:123456 }
只讀屬性readonly
:
interface Point{ userName:string|number password:number,email?:string,readonly address:string } let value:Point={ userName:'[email protected]',password:123456,address:'保定' } let val:Point={ userName:55555,address:'北京' } value.password=65975222 value.address='kkk'
函式
ts中函式可以定義返回值型別
const value=():number=>{ return 1 } const val=():string=>{ return 1 }
型別自推
在我們定義變數時沒有賦予型別,則會按照值做推論
let value=5555 value='string'
聯合型別(二選一甚至多選一)
let value:string|number value='涼宸' value=520 value=true
型別斷言:
function get(data:string|number):number{ const str=data as string if(str.length){ return str.length }else { const num = data as number return num.toString().length } } console.log(get('涼宸')); console.log(get(520));
- 使用 as 進行斷言
- 斷言不是型別轉換,斷言後只是告訴編譯器變數的型別,後面使用變數時就有提示了
- 如果不新增斷言,使用某個型別的方式就會報錯
type guard:
type guard
不是一種型別,而是一種能夠確認具體型別的一種機制
function get(data:string|number):number{ if(typeof data==='string'){ return data.length }else { return data.toString().length } } console.log(get('涼宸')); console.log(get(520));
class
class:類,ES6語法,是js面向物件晉升,class 僅僅是語法糖,底層仍然是基於函式和原型實現的
- 類:定義了一切事物抽象特點,像是一張藍圖客棧、一張圖紙
- 物件:類的例項
- 三大特徵:封裝、繼承、多型
三個修飾符,可以控制類中成員的訪問級別:
- Public:修飾的屬性或方法是公有的,任何地方都可以訪問,預設行為
- Protected:修飾的屬性或者方法是受保護的,只有類本身和其子類可以訪問
- Private:修飾的屬性或者方法是私有的,只有類內部可以訪問呢
class Person { public name:string protected age:number private address:string constructor(name:string,age:number,address:string){ this.name=name this.age=age this.address=address } speak(){ console.log(`Person:${this.name}---${this.age}---${this.address}`) } } const Children = new Person('涼宸','保定') Children.speak() // 可以正常輸出
class Person { public name:string protected age:number private address:string constructor(name:string,address:string){ this.name=name this.age=age this.address=address } speak(){ console.log(`Person:${this.name}---${this.age}---${this.address}`) } } class child extends Person{ say(){ console.log(`www.cppcns.comchild:${this.name}---${this.age}`) } } // const Children = new Person('涼宸','保定') // Children.speak() const childs = new child('涼宸','保定') childs.say()
執行時也是報錯的
class Person { public name:string protected age:number private address:string constructor(name:string,age:number,address:string){ this.name=name this.age=age this.address=address } speak(){ console.log(`Person:${this.name}---${this.age}---${this.address}`) } } class child extends Person{ say(){ console.log(`child:${this.name}---${this.age}`) } } // const Children = new Person('涼宸','保定') childs.say()
class Person { public name:string protected age:number private address:string constructor(name:string,address:string){ this.name=name this.age=age this.address=address } speak(){ console.log(`Person:${this.name}---${this.age}---${this.address}`) } } class child extends Person{ say(){ console.log(`child:${this.name}---${this.age}`) } } const Children = new Person('涼宸','保定') Children.speak() console.log(Children.address); console.log(Children.age); // const childs = new child('涼宸','保定') // childs.say()
列舉
列舉(Enum)型別用於取值被限定在一定範圍內的場景
enum Week { SUNDAY = '週日',MONDAY = '週一',TUESDAY = '週二',WEDNESDAY = '週三',THURSDAY = '週四',FRIDAY = '週五',SATURDAY = '週六' } function getProgramme(date: Week): string { if (date === Week.SUNDAY) { return '週日休閒娛樂' } else if (date === Week.MONDAY) { return '週一做博文' } else if (date === Week.TUESDAY) { return '週二衝刺' } else if (date === Week.WEDNESDAY) { return '週三繼續奮鬥' } else if (date === Week.THURSDAY) { return '週四發新文' } else if (date === Week.FRIDAY) { return '週五準備休息' } else { return '週六睡覺' } } console.log(getProgramme(Week.THURSDAY));
到此這篇關於一文了解TypeScript資料型別的文章就介紹到這了,更多相關TypeScript資料型別內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!