友好的 TypeScript 初学者指南
TypeScript是一种通过添加类型来扩展JavaScript的编程语言。它通过捕捉错误来节省时间,并在你运行代码之前提供修复。TypeScript是一种常用的添加静态类型的工具。
用TypeScript编写的代码可以通过TypeScript编译器或babel轻松转化为JavaScript。编译后的JavaScript代码总是比较干净,没有BUG,而且可以在浏览器或Node.js应用程序中运行。
目录
- TypeScript基础知识
- 编译器配置
- 类和接口
- 类型描述的特点
- 命名空间和模块
- 资源
- 结论
前提条件
在我们继续之前,建议具备以下条件。
- 对JavaScript有基本的了解。
在这篇文章中,我将向你展示一些学习Typescript时需要遵循的重要准则。但同样关键的是要记住,练习是最好的学习方法。
让我们开始吧!
TypeScript类型
布尔型
这种数据类型只是一个真/假值。下面的例子显示了你如何在TypeScript中为一个变量分配一个布尔值。
let isOpen: Boolean = true;
数值
TypeScripts支持浮点值,这种类型被称为number 。在ECMAScript 2015中,引入了八进制字元和二进制,这在TypeScript中也被支持。
let decimalExample: number = 6;
let hexExample: number = 0xf00d;
let octalExample: number = 0o744;
let bigExample: bigint = 100n;
let binaryExample: number = 0b1010;
字符串
TypeScript使用单(')或双(")引号,类似于JavaScript。文本数据类型在其他语言中被称为类型string 。
let colour: string = "yellow";
colour = 'white';
模板字符串在TypeScript中也是有效的,可以不受限制的使用。这是用backtick(`)表示的,它也可以用于嵌入表达式,如下图所示。
let fullName: string = `Idris Olubisi`;
let age: number = 47;
let text: string = `Hello, my name is ${fullName}.`
枚举
TypeScript中的枚举是一个特殊的类,包含常量值,默认枚举的编号从零开始。这种类型被归类为给一组数字值赋予令人敬畏的名字的一种手段。
enum Fruits {
Orange,
Apple,
Banana,
}
// can be accessed by
let c: Fruits = Fruits.Apple;
你可以通过设置其数值来手动设置枚举的编号,如下所示。
enum Fruits {
Orange = 1,
Apple = 4,
Banana = 7
}
// can be accessed by
let c: Fruits = Fruits.Banana;
数组
TypeScript也支持数组。一个数组是一个由一组元素组成的数据结构。每个元素由一个索引或键定义,并以这样的方式存储,即数学公式可以从其索引元组中计算其位置。
关于数组的提示
- 一旦一个数组被初始化,它就不能被调整大小,因为它是静态的。这在很多情况下是很有用的。
- 当一个数组被声明时,连续的内存块被分配。
- 一个数组在使用前需要声明。
let listOfNumbers: number[] = [1, 2, 3, 4, 5, 6];
使用通用的数组类型声明。
let listOfNumbers: Array<number> = [1, 2, 3, 4, 5, 6];
对象
一个对象是一个包含一组键值对的实例。类型object ,是一个非原始类型。
下面是一个例子。
var person = {
firstName:"Idris",
lastName:"Olubisi"
};
任何
Any 类型允许我们为一个变量分配 "任何 "特定值,类似于我们在JavaScript中的做法。any 类型允许你在编译过程中逐步控制检查类型的选入和选出。
类型Any 的一个例子如下所示。
let amount: any;
amount = 26;
amount = true;
amount = "Hello World";
amount = [];
amount = {};
amount = null;
amount = undefined;
未知
这与Any 的工作原理类似,但是,当你试图重新分配一个已经被初始化的值时,它会给出一个错误。这意味着任何东西都可以被分配给未知的本身,也可以在TypeScript中分配给any 类型。
let amount: unknown;
// Error
let newAmount: number = amount;
一个更高级的类型指南可以用于更具体的东西来检查类型。
const maybeItsUnknown: unknown;
// Check if its true
if (maybeItsUnknown === true) {
// maybeItsUnknown is a boolean
const booleanExample: boolean = maybeItsUnknown;
// It cannot be a string
const stringExample: string = maybeItsUnknown;
}
// Check if its true
if (typeof maybeItsUnknown === "string") {
// maybeItsUnknown is a string
const anotherBoolean: string = maybeItsUnknown;
// It cannot be a boolean
const anotherString: boolean = maybeItsUnknown;
虚数
在TypeScript中,一个void 类型被看作是一个不返回值的函数的返回类型。
一个例子显示在下面。
function greetings(): void {
console.log("Hi everyone ????");
}
编译器配置
tsconfig.json 指定TypeScript中的根文件和编译器选项,只要在本地运行 ,就需要编译该项目。tsc
比如说。
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* 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. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* 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 type checking. */
"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. */
"noEmitOnError": true,
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
// "exclude": [
// "node_modules" exclude by default
// ]
}
大部分的配置都被注释掉了,但是你可以在阅读了右侧附加的描述后,在必要的地方取消注释。
要运行你的TypeScript文件
- 使用
tsconfig.json文件配置typescript。 - 运行
tsc --watch,这样每次你修改.ts文件时,tsc就会编译它并在任何配置的文件夹中产生输出,比如dist文件夹。 - Nodemon可以用来观察dist文件夹中改变的文件,然后自动重新加载发生。
在package.json 中配置你的脚本,使其看起来像这样。
"scripts": {
"clean": "rimraf dist",
"build": "tsc",
"watch:build": "tsc --watch",
"watch:server": "nodemon './dist/index.js' --watch './dist'",
"start": "npm-run-all clean build --parallel watch:build watch:server --print-label"
},
类和接口
接口是一个结构化的属性组,用来描述一个对象。
一个类是一个蓝图,因此可以使用相同的属性和方法来创建和配置对象。
除了类的定义之外。
字段 - 类中的字段代表与对象有关的数据。
构造器 - 它们负责为类的对象分配内存。
函数 - 函数也被称为方法,它们代表一个对象可以采取的行动。
接口
interface IStudent {
studentCode: number;
studentName: string;
getIncome: (number) => number; // arrow function
getStudentAdvisor(number): string;
}
类
class WelcomeMessage {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Welcome, " + this.greeting;
}
}
let welcomeUser = new WelcomeMessage("Idris"); // Welcome Idris
类型描述的特点
JavaScript使用 "动态类型"(在运行时解决),Typescript使用 "静态类型"(在开发时设置)。

命名空间和模块
命名空间
命名空间用于逻辑分组,可以包括函数、类和接口以支持一组相关的功能。
命名空间在网络应用程序中的代码结构是这样的:所有的依赖关系都可以包含在一个script 标签中。
模块
TypeScript中的模块可以包含声明、代码和对模块加载器或支持ES模块的运行时的依赖性。他们提供了强大的隔离/分离关注,可重用的代码,并为捆绑提供了巨大的支持。
模块被推荐用于代码组织机制,以适应任何适当的业务逻辑。
总结
实践出真知,你会学到并找到你从未想象过的解决方案。"Jo Bradford"
我希望你觉得这个教程很有用。