账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    TypeScript绕过编译器检查的一点困惑
    32
    0

    在学习TypeScript过程中,遇到一点问题,先看下面的代码

    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;
    }
    
    createSquare({height: 200, width: 100 });    // 报错
    
    /**
     之前提问写的,这里实际是错误的
     let param = { height: 200 }
    
     createSquare(param);    // 正确
    */
    
    
    //2月21日 更正
    let param = { height: 200, width: 100 };
    
    createSquare(param);    // 正确
    

    接口规定参数只能传color, width;而我传入了height,所以出错了。但是在TypeScript中文网额外的类型检查一节中,给出了代码中规避编译器报错的解决方法。

    我的困惑是,为什么这种方法能规避编译器类型检查?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部