typescript接口数组-如何在 TypeScript 中使用套接字

本文与您分享如何在 TypeScript 中使用套接字。 小编觉得很实用,所以分享给大家作为参考,跟着小编来看看吧。

总体介绍

在 TypeScript 中,接口的作用是命名这些类型并为您的代码或第三方代码定义契约。

界面

例子:

  function printLabel(labelledObj: { label: string }) {
   console.log(labelledObj.label);
  }
  let myObj = { size: 10, label: "Size 10 Object" };
  printLabel(myObj);

typescript接口数组_typescript_数组接口400

printLabel 函数有一个参数,该参数必须是一个对象,并且有一个名为 label 的字符串类型的属性

有时我们传入多个参数,但只测量指定的参数

使用socket来实现里面的案例:

interface LabelledValue {
   label: string;
  }
  function printLabel(labelledObj: LabelledValue) {
   console.log(labelledObj.label);
  }
  let myObj = {size: 10, label: "Size 10 Object"};
  printLabel(myObj);

注:使用关键字interface

可选属性

typescript接口数组_typescript_数组接口400

有时套接字中的属性不是必需的而是可选的typescript接口数组,因此只需添加一个?就可以了

interface SquareConfig {
   color?: string;
   width?: number;
  }
  function createSquare(config: SquareConfig): {color: string; area: number} {
   let newSquare = {color: "white", area: 100};
   if (config.color) {
    newSquare.color = config.color;
   }
   if (config.width) {
    newSquare.area = config.width * config.width;
   }
   return newSquare;
  }
  let mySquare = createSquare({color: "black"});

上面代码中,config:SquareConfig指定了函数参数,{color: string;area: numner}指定了函数返回值的类型

使用可选属性的好处:

1. 可以定义可能的属性

2. 访问不存在的属性时可以捕获错误

只读属性

如果您希望某个值是只读且无法更改的,则可以使用 readonly

interface Point {
    readonly x: number;
    readonly y: number;
  }
  let p1: Point = { x: 10, y: 20 };
  p1.x = 5; // error!

TypeScript 有一个 ReadonlyArray 类型,它与 Array 类似,只不过消除了对可变方法的恐惧,因此可以确保字段创建后无法更改:

  let a: number[] = [1, 2, 3, 4];
  let ro: ReadonlyArray = a;
  ro[0] = 12; // error!
  ro.push(5); // error!
  ro.length = 100; // error!
  a = ro; // error!

额外财产检查

看一个例子:

interface SquareConfig {
    color?: string;
    width?: number;
  }
  function createSquare(config: SquareConfig): { color: string; area: number } {
    // ...
  }
  let mySquare = createSquare({ colour: "red", width: 100 });

起初你会认为这是对的,接口定义了两个可选属性color和width。 该函数实际上传入了宽度属性和一个不是套接字定义的颜色属性,但是这段代码会报错。

对象字面量会被特殊对待,并在将其作为参数传递给变量或作为参数时接受额外的属性检查。 如果对象字面量具有“目标类型”不包含的任何属性,您将收到错误。

最好的解决方案是添加字符串索引签名

  interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any;
  }

数组接口400_typescript_typescript接口数组

功能类型

例子:

interface SearchFunc {
   (source: string, subString: string): boolean;
  }
  let mySearch: SearchFunc;
  mySearch = function(src, sub) {
    let result = src.search(sub);
    if (result == -1) {
      return false;
    }
    else {
      return true;
    }
  }

可转位型

可索引类型,例如 a[10] 或 obj['a']。 可索引类型具有索引签名,它描述索引对象的类型以及相应的索引返回类型。

interface StringArray {
   [index: number]: string;
  }
  let myArray: StringArray;
  myArray = ["Bob", "Fred"];
  let myStr: string = myArray[0];

感谢您的阅读! 这篇关于《如何在 TypeScript 中使用套接字》的文章就分享到这里。 希望以上内容能够对您有所帮助,让您学到更多的知识。 如果您觉得文章不错typescript接口数组,可以分享出去,让更多的人看到。 人们看到了!