猿问

急求!!!!TypeScript绕过编译器检查的一点困惑求解答!

在学习TypeScript过程中,遇到一点问题,先看下面的代码
interfaceSquareConfig{
color?:string;
width?:number;
}
functioncreateSquare(config:SquareConfig):{color:string;area:number}{
letnewSquare={color:"white",area:100};
if(config.color){
newSquare.color=config.color;
}
if(config.width){
newSquare.area=config.width*config.width;
}
returnnewSquare;
}
createSquare({height:200,width:100});//报错
/**
之前提问写的,这里实际是错误的
letparam={height:200}
createSquare(param);//正确
*/
//2月21日更正
letparam={height:200,width:100};
createSquare(param);//正确
接口规定参数只能传color,width;而我传入了height,所以出错了。但是在TypeScript中文网额外的类型检查一节中,给出了代码中规避编译器报错的解决方法。
我的困惑是,为什么这种方法能规避编译器类型检查?
至尊宝的传说
浏览 362回答 2
2回答

波斯汪

我这边最后一行也是错误的楼主没有好好看文档,文档说的绕过检测的方式代码是这样的,由于有[propName:string]:any,它是可以允许传入有任意字段名的对象interfaceSquareConfig{color?:string;width?:number;[propName:string]:any;}letsquareOptions={colour:"red",width:100};letmySquare=createSquare(squareOptions);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答