【TypeScript】基礎型別和高階型別
技術標籤:typescriptjavascript
一、安裝和使用
1,全域性環境安裝: npm install -g typescript
2,編譯:tsc hello.ts
二、基礎型別:
1,布林值: let isDone:boolean = false;
2,數值: let a:number = 6; 可以賦值二進位制,八進位制,十六進位制;
3,字串: let name:string = "Tom "; 可以使用模板字串 `${name}`
4,任意型別:let some:any = "hello";
5,陣列:let num:number[] = [1,2,3];
聯合型別陣列: let num:(number|string)[] = [1,2,3,"4","5"];
泛型陣列:let num:Array<number> = [1,2,3,4];
6,元組(Tuple):
表示一個已知元素數量和型別的陣列,各元素的型別不必相同;
let list:[number,string] = [1,'2']; // 不能多不能少,型別也不能不一樣
7,列舉(enum):
enum Coror {Red,Green,Blue} 等價於 enum Coror{Red=0,Green=1,Blue=2} // 可以手動賦值。最後一個數字決定起始值;
反向得到他的鍵值 enum Color {Red=1,Green=2,Blue=4} Color[2] = 'Green';
8,void: 表示不是任意型別,一般出現在函式中,用來標記函式沒有返回值;
void型別對應2個值, 一個是undefined,一個null;
9,null 和 undefined:
預設情況下null和undefined是所有型別的子型別
三、高階型別:
1,介面(interface)
interface Article { title: string; count: number; content:string; fromSite: string; } const article: Article = { title: '好好學習TypeScript', count: 9999, content: 'xxx...', fromSite: 'baidu.com' }
在賦值時,如果任何一個欄位沒有被賦值或者欄位對應的資料型別不對, ts都會提示錯誤。
1.1,非必填(?):
當某個欄位不是必填時,可以宣告非必填,
interface Article {
title: stirng;
count: number;
content:string;
fromSite?: string; // 非必填
}
// 不會報錯
const article: Article = {
title: '為vue3學點typescript(2), 型別',
count: 9999,
content: 'xxx...',
}
1.2 用介面定義函式:
// 宣告介面
interface Core {
(n:number, s:string):[number,string]
}
// 宣告函式遵循介面定義
const core:Core = (a,b)=>{
return [a,b];
}
1.3 用介面定義類
// 定義
interface Animal {
head:number;
body:number;
foot:number;
eat(food:string):void;
say(word:string):string;
}
// implements
class Dog implements Animal{
head=1;
body=1;
foot=1;
eat(food:string){
console.log(food);
}
say(word:string){
return word;
}
}
2,交叉型別(&):
交叉型別是將多個型別合併為一個型別,表示"並且"的關係,用 &連線多個型別, 常用於物件合併;
interface A {a:number,c:string};
interface B {b:string};
const a:A = {a:1,c:'2'};
const b:B = {b:'1'};
const ab:A&B = {...a,...b};
console.log(ab.c) // 2
3,聯合型別(|):
聯合型別也是將多個型別合併為一個型別, 表示"或"的關係,用|
連線多個型別;
function setWidth(el: HTMLElement, width: string | number) {
el.style.width = 'number' === typeof width ? `${width}px` : width;
}
4,泛型型別:
用型別變數去描述一個型別(類型範圍);
1)泛型型別:
function convert<T>(input:T):T{
return input;
}
// 定義泛型型別
interface Convert {
<T>(input:T):T
}
// 驗證下
let convert2:Convert = convert // 正確不報錯
2)泛型介面:
interface Goods<T>{
id:number;
title: string;
size: T;
}
let apple:Goods<string> = {id:1,title: '蘋果', size: 'large'};
let shoes:Goods<number> = {id:1,title: '蘋果', size: 43};