TypeScript接口可选属性和返回类型
我是typescript新手,现在回顾一下文档,在“可选属性”部分有一个示例:TypeScript接口可选属性和返回类型,typescript,Typescript,我是typescript新手,现在回顾一下文档,在“可选属性”部分有一个示例: interface SquareConfig { color?: string; width?: number; } function createSquare(config: SquareConfig): { color: string; area: number } { let newSquare = { color: "white", area: 100 }; if (config.color
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}
。这是因为他们想对变量color
和area
进行类型检查吗?如果是这样的话,为什么他们把它们写在函数参数中,而不是放在函数中,然后像下面那样进行类型检查
let color:string;
let area: number;
你能解释一下它在这段代码中的作用吗 代码的这一部分说明了此函数预期返回的内容。您正在返回newSquare,它是一个包含颜色和区域属性的对象 将
{color:string;area:number}
声明为返回类型的原因是指定函数将始终返回颜色和面积值,它们不再是可选的
使用该函数时,不必检查返回的属性是否未定义或为null
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
}
在typescript中,函数返回类型在colun之后定义: 因此,函数返回类型可以简单为 1-无任何内容将:无效 例如:
function createSquare(config: SquareConfig): void {
// some code
alert('just not returned code');
}
2-数字:数字,字符串:字符串
function createSquare(config: SquareConfig): string {
// some code
return 'some strings ';
}
3-数字数组:数组或字符串:数组
function createSquare(config: SquareConfig) :Array<string> {
// some code
return ['some strings '];
}
在这种情况下,接口以更简单的方式帮助我们编写以下代码
interface AnyTypeAsReturn {
color: string;
area: number ;
}
function createSquare() :AnyTypeAsReturn {
return { color: 'red', area: 5 }
}
const square = createSquare();
它简化了我们编写代码的方式,并可在我们的应用程序中重用这是否回答了您的问题?是的,这很有帮助……但我不知道TS3中的“返回类型”不返回数组
interface AnyTypeAsReturn {
color: string;
area: number ;
}
function createSquare() :AnyTypeAsReturn {
return { color: 'red', area: 5 }
}
const square = createSquare();