文章目錄
- TypeScript相關問題及知識點
- Q1: ts中type和interface的區別?
- A1: 有相同點與不同點,具體內容如下,
- Q2: ts中interface和class的區別? 分別什么時候使用?
- A2: interface和class都能定義資料模型,區別:……
- Q3: ts中的泛型有什么了解?
- A3: 案例
- 1. 不用泛型的話,這個函式可能是下面這樣:
- 2. 泛型的使用方法有兩種:
TypeScript相關問題及知識點
Q1: ts中type和interface的區別?
A1: 有相同點與不同點,具體內容如下,
1. 相同點:
(1) 兩者都可以定義物件和函式,
interface:
interface Person{
name: string;
age: number;
}
interface SetPerson {
(name: string, age: number): void;
}
type:
type Person= {
name: string;
age: number
};
type SetPerson = (name: string, age: number)=> void;
(2) 都可以繼承,
interface 定義的物件用extends繼承,type用&繼承,二者之間可以用前面提到的自己的語法互相繼承,
2. 不同點:
(1)interface可以宣告合并,即宣告了多個同樣名稱的介面可以合并成一個,而type不行,
interface Pesron{
name: string;
age: number;
}
interface Person{
sex: string;
}
/*
Person介面為 {
name: string;
age: number;
sex: string ;
}
*/
(2) type可以宣告:基本型別的別名、聯合型別、元組等型別,而interface不行,
// 別名
type Empty=null;
// 聯合型別
interface Person1{
sayHi();
}
interface Person2{
eat();
}
type Person = Person1 | Person2;
type ex = number | string;
// 元組 陣列中元素的資料型別都一般是相同的(any[] 型別的陣列可以不同),如果存盤的元素資料型別不同,則需要使用元組,
type tuple=[1,'good'];
//type 陳述句中可以使用 typeof 獲取實體的型別進行賦值
let tem = new Number();
type B = typeof tem;
(3)還有其他復雜操作,泛型等,
Q2: ts中interface和class的區別? 分別什么時候使用?
A2: interface和class都能定義資料模型,區別:……
區別:interface只是用來宣告物件型別或方法,不做實作;而class是類的宣告并實作,
- 簡單的資料模型,直接用于展示的,用 interface 進行定義;
- 比較復雜的資料模型,有欄位屬性定義以及一些方法,就需要使用 class ,里面還有
constructor建構式, - interface 只在編譯時用于型別檢查,class 編譯完成之后實際上就是 javascript 中的原型(prototype),
介面可以通過extends繼承類,類可以通過implements去實作介面,有個很好的例子幫助理解,
Q3: ts中的泛型有什么了解?
A3: 案例
1. 不用泛型的話,這個函式可能是下面這樣:
function identity(arg: number): number {
return arg;
}
或者,我們使用any型別來定義函式:
function identity(arg: any): any {
return arg;
}
any的情況,可以是任何型別,因此,我們需要一種方法使回傳值的型別與傳入引數的型別是相同的, 這時,就用到了T,型別變數,它是一種特殊的變數,只用于表示型別而不是值,
function identity<T>(arg: T): T {
return arg;
}
這樣就可以跟蹤函式里使用的型別資訊,
2. 泛型的使用方法有兩種:
此處參考官方檔案改寫,
(1) 尖括號的形式:
let output = identity< string> (“myString”);// type of output will be ‘string’
這里明確的指定了T是string型別,并做為一個引數傳給函式,使用了<>括起來,
(2) 利用了型別推論,即編譯器會根據傳入的引數自動地幫助我們確定T的型別:
let output = identity(“myString”); // type of output will be ‘string’
本文為原創文章,轉載請注明出處,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/292398.html
標籤:其他
