小工具知识网

当前位置: 首页 > 行业知识 > 前端 TS

行业知识

前端 TS

2026-11-15 23:52:31 来源:互联网转载
  • 类型:

    类型例子描述
    number1, -33, 2.5任意数字
    string‘hi’, “hi”, hi任意字符串
    booleantrue、false布尔值true或false
    字面量其本身限制变量的值就是该字面量的值
    any*任意类型
    unknown*类型安全的any
    void空值(undefined)没有值(或undefined)
    never没有值不能是任何值,只能抛出异常
    object{name:‘孙悟空’}任意的JS对象
    array[1,2,3]任意JS数组
    tuple[4,5]元素,TS新增类型,固定长度数组
    enumenum{A, B}枚举,TS中新增类型
  • 用法

    • number

      let decimal: number = 6;let hex: number = 0xf00d;let big: bigint = 100n;
    • boolean

      let isDone: boolean = false;
    • string

      let color: string = "blue";color = 'red';
    • 字面量

    • 也可以使用字面量去指定变量的类型,通过字面量可以确定变量的取值范围

      let color: 'red' | 'blue' | 'black';let num: 1 | 2 | 3 | 4 | 5;
    • any

      let d: any = 4;d = 'hello';d = true;
    • unknown

      let notSure: unknown = 4;notSure = 'hello';
    • void

      let unusable: void = undefined;function fn(): void{}function fn(): void {   return undefined}
    • never

      function error(message: string): never {   throw new Error(message);}
    • object(没啥用)

      let obj: object = {};
    • array

      let list: number[] = [1, 2, 3];let list: Array = [1, 2, 3];
    • tuple

      let x: [string, number];x = ["hello", 10]; 
    • enum

      enum Color {   Red,   // 0   Green, // 1   Blue,  // 2}let c: Color = Color.Green;enum Color {   Red = 1,  // 1   Green,    // 2   Blue,     // 3}let c: Color = Color.Green;enum Color {   Red = 1,    // 1   Green = 2,  // 2   Blue = 4,   // 4}let c: Color = Color.Green;
    • 断言

            //写法1      let someValue: unknown = "this is a string";      let strLength: number = (someValue as string).length;      //写法2      let someValue: unknown = "this is a string";      let strLength: number = (someValue).length;      ```
    • 接口

      • 接口的作用类似于没有实际值的抽象类
      • 可以用于定义对象,方法的参数/返回值,接口(使用extends关键字),类(使用implements关键字)的结构
        //对象interface Info {   name: string   age: number   say?: () => void}const user: Info = {   name: '张三',   age: 18,   say: () => {      console.log(`我叫${this.name}`)   }}//方法的参数和返回值interface sum {   (a: number, b: number): number}const add: sum = (a, b) => {   return a + b;}sum(1, 2)// 接口interface Person{   name: string;   say():void;}interface man extends Person{   eat():void;}// 类interface Person{   name: string;   say():void;}interface Student{   hello():void;}// 同时执行多个接口,用`,`隔开class Student implements Person,Student{   constructor(public name: string) {}   say() {      console.log(`我叫${this.name}`);   }   hello() {      console.log(`我是一个学生`);   }}
      • Class (链接: link)

      • 泛型(链接:link)

      • 补充

        • declare关键字 :用来告诉编译器,某个类型是存在的,可以在当前文件中使用。只能定义类型,不能直接赋值
          declare var document;document.title = 'Hello';declare function sayHello(  name:string):void;sayHello('张三');

上一篇:登录服务器类型在哪里看?

下一篇:平台服务器种类怎么选?