Ts初识

发布于 2023-03-16  29 次阅读


概念

  • TS 是 JS 的超集
  • TS 是静态类型(强类型)
  • JS 是动态类型(弱类型)
  • TS 需要经过编译转换成 JS 才能在浏览器上运行
  • TS 能够在编写阶段检查错误

最终运行的还是JavaScript:

安装

npm i -g typescript ts-node

检查是否安装好:

tsc --help # tsc -> typescript compiler 缩写

假数据提供服务网站

https://jsonplaceholder.typicode.com/

使用

转换运行

import axios from 'axios';

const url = '<https://jsonplaceholder.typicode.com/todos/1>';

axios.get(url).then(res => {
  console.log(res.data);
});

执行命令:

tsc index.ts # 生成js文件
node index.js # node环境下执行js

合并执行:

  • 利用 node-ts 包合并两个命令执行
npm i @types/node -S
  • 执行:
ts-node index.ts

应用

import axios from 'axios';

const url = '<https://jsonplaceholder.typicode.com/todos/1>';

interface Todo {
  id: number,
  title: string,
  completed: boolean
}

axios.get(url).then(res => {
  const todo = res.data as Todo;

  const ID = todo.Id;
  const Title = todo.Title;
  const Finished = todo.finished;

  console.log(`
    这个todo的ID为: ${ID},
    它的标题是: ${Title},
    是否完成: ${Finished}
  `);
});

错误提示

  • 能够在编译阶段就能看到报错
  • 能够发现参数传递错误
import axios from 'axios';

const url = '<https://jsonplaceholder.typicode.com/todos/1>';

interface Todo {
  id: number,
  title: string,
  completed: boolean
}

axios.get(url).then(res => {
  const todo = res.data as Todo;

  const id = todo.id;
  const title = todo.title;
  const completed = todo.completed;

  logTodo(id, completed, title);
});

const logTodo = (id: number, title: string, completed: boolean) => {
  console.log(`
    这个todo的ID为: ${id},
    它的标题是: ${title},
    是否完成: ${completed}
  `);
}

类型注解和类型推断

类型断言

有时候你会遇到这样的情况,你会比TypeScript更了解某个值的详细信息。 通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。

通过类型断言这种方式可以告诉编译器,“相信我,我知道自己在干什么”。 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript会假设你,程序员,已经进行了必须的检查。

类型断言有两种形式。 其一是“尖括号”语法:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

另一个为as语法:

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

两种形式是等价的。 至于使用哪个大多数情况下是凭个人喜好;然而,当你在TypeScript里使用JSX时,只有 as语法断言是被允许的。

最后更新于 2023-07-20