TypeScript接口可选属性文档示例

问题描述 投票:0回答:4

我是打字稿新手,现在浏览文档,“可选属性”部分中有此示例:

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" });

现在,我确实了解什么是可选属性,但是让我感到困惑的是函数参数中的: { color: string; area: number }。是因为他们想对变量colorarea进行类型检查吗?如果是这种情况,为什么他们将它们写在函数参数中,而不是将它们放在函数中,并像下面这样进行类型检查

let color:string;
let area: number;

您能否解释一下此代码段的作用?

javascript typescript typescript-typings
4个回答
0
投票

代码的那部分说明了该函数将返回什么。您将返回newSquare,它是一个包含颜色和区域属性的对象。


0
投票
interface SquareConfig {
  color?: string; // means color value can either be of type string or undefined
  width?: number; // means width value can either be of type number or undefined
}

: { color: string; area: number }在函数声明中表示函数将始终具有该类型的返回值,这意味着函数createSquare将采用类型为SquareConfig的参数,并且返回值将为类型为{ color: string; area: number}的对象]

function createSquare(config: SquareConfig): { color: string; area: number } {

   // code....

   // you must return an object with property color of type string
   // and property area of type number otherwise you will get a compiler error

}

0
投票

{ color: string; area: number }声明为返回类型的原因是,指定该函数将始终返回颜色和区域值,它们不再是可选的。

使用该函数时,您不必检查返回的属性是否未定义或为null。


0
投票

typescript中,function返回类型是在coluns之后定义的:所以函数的返回类型可以很简单,例如

1-没什么会是:void

示例:

function createSquare(config: SquareConfig): void {
// some code 
alert('just not returned code');
}

2-数字:数字,字符串:字符串

function createSquare(config: SquareConfig): string {
 // some code 
 return 'some strings ';
}

3-数字数组[[:Array或字符串:Array

function createSquare(config: SquareConfig) :Array<string> { // some code return 'some strings '; }
4- a(复杂类型),像和对象一样包含两个属性对象。

{color:字符串;区域:数字}

这意味着该函数将返回一个具有两种颜色的对象,其值应为字符串,另一个属性将被命名为area,其值仅接受数字。

function createSquare() :{ color: string; area: number } { return { color: 'red', area: 5 }; } console.log(createSquare());

在这种情况下,接口可以通过以下更简单的方式帮助我们编写代码。

interface AnyTypeAsReturn { color: string; area: number ; } function createSquare() :AnyTypeAsReturn { return { color: 'red', area: 5 } } const square = createSquare();

它简化了我们编写代码的方式,并且可以在我们的应用程序中重复使用
© www.soinside.com 2019 - 2024. All rights reserved.