一、主要用途

主要用于他人调用时,防止出错

1、引例

  • 常规的方法定义,容易导致出错 ```typescript // 他人调用方法时,常会导致错误调用,且无任何错误提示 const show = (name, age) => { console.log(“名字为:”, name, “,年龄为:”, age); }

show(null, “你爸爸”);

  1. <a name="xHE32"></a>
  2. #### 2、解决方案
  3. - 使用接口来强制定义变量
  4. ```typescript
  5. interface IShowType {
  6. name: string;
  7. age: number;
  8. }
  9. const show = (st: IShowType): string => {
  10. return "名字为:" + st.name + ",年龄为:" + st.age;
  11. }
  12. let result = show({name: "哈啊哈哈", age: 11});
  13. console.log(result);
  • 写法错误的情况下在编译时会报错,但运行后控制台不会报错

image.pngimage.png

3、区分错误的写法

const show = (st: IShowType): string => {
  return "名字为:" + name + ",年龄为:" + age;        // 必须形如 st.age
}
let result = show(name: "哈啊哈哈", age: 11);        // 必须形如 {name: "哈啊哈哈", age: 11}

二、更多用法

1、类型定义

  • 正确用法 ```typescript interface IShowType { name: string; age: number; [propName: string]: any // 键值对, key 必须为 string // weight ?: number; // 可选变量 }

const show = (st: IShowType): string => { return st.name + “ - “ + st.age + “ - “ + st.aKey; }

let result = show({name: “哈啊哈哈”, age: 11, aKey: “值aaa”}); console.log(result);

<a name="DjmmE"></a>
#### <br />

- 错误用法
```typescript
interface IShowType {
  // ...
  age: number;
  [propName: string]: string  //  若这样写会出错
  // ...
}
// 因为 age: 11 也会被匹配进 [propName: string]: string,同时 11 并不是字符串,出错
let result = show({name: "哈啊哈哈", age: 11, aKey: "值aaa"});

2、函数定义

interface IFunc {
  (name: string, age: number): void
}

// 定义函数接口后,仍需要再次定义一次规则,感觉很鸡肋
const show: IFunc = (name: string, age: number) => {
  console.log(name, age);
}

show("哈啊哈哈", 11);