首页 > 看了typescript接口的可选属性,如果我有一些必选和一些不必选的,我怎么定义?

看了typescript接口的可选属性,如果我有一些必选和一些不必选的,我怎么定义?

看了typescript接口的可选属性,如果我有一些必选和一些不必选的。我这样写代码为什么会报错,错误:

basic.data.type.ts(47,30): error TS2339: Property 'cr' does not exist on type 'SquareConfig'.
basic.data.type.ts(55,29): error TS2345: Argument of type '{ color: string; }' is not assignable to parameter of type 'SquareConfig'.
  Property 'name' is missing in type '{ color: string; }'.

代码如下:

interface SquareConfig {
  name:string;
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
  let newSquare = {color: "white", area: 100};
  if (config.color) {
    // Error: Property 'collor' does not exist on type 'SquareConfig'
    newSquare.color = config.cr;  // Type-checker can catch the mistyped name here
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let mySquare = createSquare({color: "black"});

let mySquare = createSquare({name:'Tom',color:'black'});

传的是SquareConfig这个接口定义的类型,name属性是必须的,其它两个为可选的属性

【热门文章】
【热门文章】