【TypeScript】類型聲明及應用(二)
文章來源地址http://www.zghlxwxcb.cn/news/detail-617200.html
一、前言
TypeScript開發(fā)中需要對定義的變量指定類型,目前版本都支持哪些類型,每一個類型都有哪些含義,在這篇文章中,我們將會對其進行總結說明
二、JavaScript基本數據類型以及TypeScript特有的數據類型。
- JavaScript基本數據類型: String、Number、null、undefined、Boolean、Symbol
- TypeScript數據類型:任意類型(any)、元組類型(tuple)、枚舉類型(enum)、void類型、never類型、unknown類型、類型斷言(Type Assertion)、接口類型(interface)、函數類型(Function)
具體分別含義如下
2.1 JavaScript(JS)基本數據類型包括:
- 數字(Number):表示整數和浮點數,如 1、-2、3.14 等。
- 字符串(String):表示文本數據,用單引號(')或雙引號(")括起來,如 ‘hello’、“world” 等。
- 布爾值(Boolean):表示真或假,只有兩個值,true 和 false。
- null:表示空值,即沒有任何值的變量。
- undefined:表示未定義,即變量聲明了但沒有賦值。
- Symbol:表示唯一的標識符,通常用于對象屬性的鍵名。
注意,JS 還有一種復雜數據類型,即對象(Object),它可以包含多個屬性,每個屬性是一個鍵值對。對象的屬性可以是基本數據類型或其他對象,甚至可以是函數。
2.2 TypeScript 特有的數據類型包括:
- 任意類型(any):表示可以是任何類型。
- 元組類型(tuple):表示有限數量的未知類型元素的數組。
- 枚舉類型(enum):表示具有命名值的一組相關的常量。
- void類型:表示沒有任何類型,常用于函數的返回值類型。
- never類型:表示永遠不存在的值的類型。
- unknown類型:表示任何類型的值,但在使用前必須先進行類型檢查。
- 類型斷言(Type Assertion):表示在某些情況下需要手動告訴編譯器變量的類型。
- 接口類型(interface):表示對象的類型。
- 函數類型(Function):表示函數的類型。
三、類型使用實踐
3.1 基礎類型的聲明和使用
String、Number、null、undefined、Boolean、Symbol基礎類型的聲明和使用
基礎類型在JavaScript中的常規(guī)寫法如下:
let name = "suwu150";
let count = 1111;
let score = null;
let address = undefined;
let isShow = false;
const nameShow = Symbol("foo");
同樣的,我們也簡單認識下TypeScript中的寫法如下:
let name: string = "suwu150";
let count: number = 1111;
let score: null = null;
let address: undefined = undefined;
let isShow: boolean = false;
const nameShow: unique symbol = Symbol("foo");
使用在線演練場或者本地編輯器進行編譯后,我們能看到以下的結果:
"use strict";
var name = "suwu150";
var count = 1111;
var score = null;
var address = undefined;
var isShow = false;
var nameShow = Symbol("foo");
注意,這個結果是在官方在線演練場中編譯后的結果,有些老鐵可能會在本地終端使用tsc進行驗證,會發(fā)現運行結果和我這個不一致,這是因為 tsconfig.json中配置compilerOptions參數,如下,當然還有很多其他的配置,具體可以查找資料:
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2022", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": [
"es2015.promise",
"dom",
"es5",
], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
在體驗了正常定義之后,我們體驗下,定義的類型和賦值類型有所差異的情況下,會有如下提示, 繼續(xù)編寫TypeScript代碼
let myName: string = "suwu150";
let count: number = 1111;
let score: null = null;
myName = 2023;
count = '平平安安'
score = 888
繼續(xù)編譯看結果
3.2 任意類型(any)
在 TypeScript 中,可以使用any類型來表示任意類型。
any類型可以接受任何類型的值,而且不會進行類型檢查。例如:
let value: any = "hello";
value = 123;
value = true;
在上面的示例中,變量value的類型為any,因此可以被賦值為字符串、數字或布爾值。
盡管any類型非常靈活,但是過度使用它可能會導致代碼難以維護和理解。在實際開發(fā)中,應該盡可能地使用更具體的類型來避免類型錯誤。
3.3 元組類型(tuple)
TypeScript中的元組類型(tuple)是一種特殊的數組類型,它允許開發(fā)人員在定義數組時指定每個元素的類型和數量,并且這些類型和數量必須與定義時一致,否則會引發(fā)類型錯誤。
元組類型的語法如下:
let myTuple: [string, number];
myTuple = ['name', 23023]
對于TypeScript中有多種形式的元祖書寫方式。
(1)使用方括號和逗號表示元組類型
let tuple: [string, number] = ["hello", 123];
(2)使用數組多元素類型表示元組類型:
let tuple: Array<string | number> = ["hello", 123];
(3)使用類型別名表示元組類型:
type Tuple = [string, number];
let tuple: Tuple = ["hello", 123];
需要注意的是,上述方式一、方式三其實是對元祖長度的一個限制。也就是不能超過指定定義的長度,否則編譯時會報錯誤提示。
let tuple: [string, number] = ["hello", 123, 4444]; // error
let tuple2: Array<string | number> = ["hello", 123, "hello", 123, 4444];
3.4 枚舉類型(enum)
TypeScript 的枚舉類型(enum)是一種具有有限數量的命名常量值的數據類型。
枚舉類型可以使代碼更易于維護和更新,因為使用枚舉可以避免在代碼中使用未知的硬編碼常量。主要分為數字枚舉、字符串枚舉、異構枚舉。
以下是一個簡單的 TypeScript 枚舉類型的例子:
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
console.log(c); // 1
(1)數字枚舉:使用數字作為枚舉成員的值。
enum Direction {
Up,
Down,
Left,
Right,
}
let value: Direction = Direction['Up']
let valueName = Direction[0]
console.log(value)//0
console.log(valueName)//Up
編譯后,如下
由運行結果可以看到,我們既可以取到枚舉成員的屬性名,也能取到枚舉成員的屬性值,它們之間是存在相互映射的關系。
(2)字符串枚舉:使用字符串作為枚舉成員的值。
enum Color {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
let stringValueVal = Color['Red']
console.log(stringValueVal)//Red
需要注意的是,對于字符串類型的枚舉,是不能對字符串類型枚舉進行數字的反向映射。
(3)異構枚舉:枚舉類型里既包含字符串又包含數字。
注意:含有字符串值成員的枚舉中也可以使用計算值。
enum BooleanLikeEnum {
No = 0,
Yes = "YES",
}
console.log(BooleanLikeEnum.No); // 0
console.log(BooleanLikeEnum.Yes); // "YES"
以上就是一個典型的異構,包含字符串和數字類型值。
同時注意,含有字符串成員值的枚舉中允許使用計算值。
enum FileAccess {
// 常量成員
START,
None = 'none',
Read = 1 << 1,
Write = 1 << 2,
ReadWrite = Read | Write,
// 計算成員
G = "123".length
}
console.log(FileAccess.Read); // 2
console.log(FileAccess.G); // 3
這種寫法沒問題,即可以使用計算值,也可以包含字符串值。
(4)計算值和常量成員
枚舉對象的成員值可以是計算出來的值也可以是常量值,如上面例子顯示,既包含了常量,也包含了計算量
enum FileAccess {
// 常量成員
None,
Read = 1 << 1,
Write = 1 << 2,
ReadWrite = Read | Write,
// 計算成員
G = "123".length
}
console.log(FileAccess.Read); // 2
console.log(FileAccess.G); // 3
3.5 void(空類型)
在 TypeScript 中,void 表示“沒有返回值”的函數或表達式。
它通常用于函數聲明和定義中,在函數簽名中表示該函數不會返回任何值。
function sayHello(): void {
console.log("Hello!");
}
在上面的示例中,sayHello() 函數不會返回任何值,因此可以使用 void 類型進行聲明。
另外,void 類型的變量只能被賦值為 undefined 或 null:
let num: void = undefined;
let str: void = null;
3.6 never(不存在的值類型)
never 是其它類型(包括 null 和 undefined)的子類型,代表從不會出現的值。
這意味著聲明為 never 類型的變量只能被 never 類型所賦值,在函數中它通常表現為拋出異常或無法執(zhí)行到終止點(例如無限循環(huán)),示例代碼如下:
let x: never;
let y: number;
// 編譯錯誤,數字類型不能轉為 never 類型
x = 123;
// 運行正確,never 類型可以賦值給 never類型
x = (()=>{ throw new Error('exception')})();
// 運行正確,never 類型可以賦值給 數字類型
y = (()=>{ throw new Error('exception')})();
// 返回值為 never 的函數可以是拋出異常的情況
function error(message: string): never {
throw new Error(message);
}
// 返回值為 never 的函數可以是無法被執(zhí)行到的終止點的情況
function loop(): never {
while (true) {}
}
3.7 unknow(未知類型)
在 TypeScript 中,未知類型表示一個值可以是任何類型。與 any 類型不同的是,未知類型不能直接賦值給其他類型,除非對其進行類型檢查或類型斷言。
以下是一個使用未知類型的示例:
let x: unknown = 10;
// 使用 typeof 操作符檢查類型
if (typeof x === 'number') {
console.log(x + 5);
}
// 使用類型斷言轉換為其他類型
let y = x as string;
console.log(y.toUpperCase());
在上面的示例中,變量 x 被定義為未知類型,并賦值為數字 10。
在第一個 if 語句中,使用 typeof 操作符檢查 x 是否為數字類型,如果是,則將其加 5 并輸出。
在第二個語句中,使用類型斷言將 x 轉換為字符串類型,并使用 toUpperCase() 方法輸出其大寫形式。
編譯后結果如下:
以上就是類型聲明和應用,感興趣的同學幫忙來個點贊關注,謝謝。文章來源:http://www.zghlxwxcb.cn/news/detail-617200.html
到了這里,關于【TypeScript】類型聲明及應用(二)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!