前端开发TypeScript入门基础教程

来自:网络
时间:2022-08-03
阅读:

TYPESCRIPT

官网

github

前端开发TypeScript入门基础教程

TypeScript是一种由微软开发的开源、跨平台的编程语言。它是JavaScript的超集,最终会被编译为JavaScript代码。

可以看看官网的5分钟 TypeScript Tooling in 5 minutes

安装 TypeScript

命令行运行如下命令,全局安装 TypeScript:

npm install -g typescript

安装完成后,在控制台运行如下命令,检查安装是否成功:

tsc -V 

第一个ts程序

新建文件 test1.js

const str:string ="hello world TS";
console.log(str)

代码是写好了,想要运行还得将ts编译为js,使用 tsc 命令,会在同层生成 js文件

tsc test1.ts

执行 node test1.js

PS E:\mysjc\ts> node test1.js
hello world TS
PS E:\mysjc\ts> 

恭喜你已经入门ts,回过头再来看看 ts和js有什么区别,细心的你已经发现 ts 多了个类型,那有人就会问了什么是类型? 有哪些类型?

  • 类型是一组关键字,声明一个标识符的基本数据类型或者抽象数据结构类型
  • 类型决定了内存到底要存什么样的数据

基础类型

type

string

使用单引号 或双引号 " 来表示字符串类型。反引号 ` 来定义多行文本和内嵌表达式

const str1: string = "hello world";
const str2: string = 'ts';
const str3: string = `年少不知富婆好,${ str1 } ${ str2 } `;

number

const num1: number = 3;// 十进制
const num2: number = 3.3;
const num3: number = 3.333;
const num4: number = 0b11;// 二进制
const num5: number = 0o12;// 八进制 
const num6: number = 0xa; // 十六进制 

boolean

逻辑值:true 和 false

const bol1: boolean=false;
const bol2: boolean=true;

数组

  • 元素类型后面接上[]
  • Array<元素类型>
const list1: number[]=[1,2,3]; // 可以试试 list1[0]='2',会发生什么。
const list2: Array<number>=[1,2,3];

枚举

enums

enum Animal {
    Dog,
    Cat,
    Pig
  }
  let zhangsan: Animal = Animal.Dog 
  console.log(zhangsan, Animal.Cat, Animal.Pig) ;// 0 1 2

输出0,1,2,我想让张三变成狗,可以直接赋值,这下张三就成真的狗了。

  enum Animal {
    Dog="狗",
    Cat="猫",
    Pig="猪"
  }
  let zhangsan: Animal = Animal.Dog 
  console.log(zhangsan, Animal.Cat, Animal.Pig) ;// 狗 猫 猪

any

可以是任意类型

let a: any = [1,undefined,null,'string',true,false];
a[0]='s';
console.log(a); //[ 's', undefined, null, 'string', true, false ] 
let b: any=1;
b='wc';
b=null;
console.log(b); //null

object

参数就是 object 类型

// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
    console.log("The coordinate's x value is " + pt.x);
    console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });

object 类型还可以指定属性是否可选

function printName(obj: { first: string; last?: string }) {
    console.log(`${obj.first}-${obj.last}`);
}
printName({ first: "Bob" }); //Bob-undefined
printName({ first: "Alice", last: "Alisson" }); //Alice-Alisson

如果可选参数不传递,获得的值 undefined,在使用之前进行检查即可。

function printName(obj: { first: string; last?: string }) {
    // obj.last.toUpperCase(); // TypeError: Cannot read property 'toUpperCase' of undefined
    if (obj.last !== undefined) {
        console.log("if", obj.last.toUpperCase());
    }
    console.log(obj.last?.toUpperCase());
}
printName({ first: "Bob" }); // undefined
/**
 * if AA
 * AA
 */
printName({ first: "Bob", last: "aa" });

Union 联合类型

联合类型是由两个或多个其他类型组成的类型

/**
 * 
 * @param id 类型只能传递 number 或者 string
 */
function work(id: number | string) {
    console.log("上班:" + id);
}
work(101);//上班:101
work("202");//  上班:202
//  work(false); 

如果联合的每个成员都有效,便可以做一些有意思的事情

/**
 * @param id 类型只能传递 number 或者 string
 */
function work(id: number | string) {
    const salary: number = 300;
    if (typeof id === "string") {
        console.log(`${id}上班,可获得薪水$${salary}`);
    } else {
        console.log(`${id}上班,可获得薪水$${salary * 2}`);
    }
}
work(101); //101上班,可获得薪水$600
work("202"); //202上班,可获得薪水$300

Type Assertions 类型断言

类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用

  • <类型>值
  • 值 as 类型
console.log(1 as string)
console.log(<string>1 )

类型推断

TS会在没有明确的指定类型的时候推测出一个类型

  • 定义变量时赋值了, 推断为对应的类型
  • 定义变量时没有赋值, 推断为any类型
let a = 1;
a = '11';//不能将类型“string”分配给类型“number”
let b;
b = 1;
b = '1';
b = null;

以上就是前端开发TypeScript入门基础教程的详细内容,更多关于TypeScript入门基础的资料请关注其它相关文章!

返回顶部
顶部