超额财产检查如何提供帮助? [英] How excess property check helps?

查看:91
本文介绍了超额财产检查如何提供帮助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,

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

interface Square{
    color: string;
    area: number;
}

function createSquare(config: SquareConfig): Square {

    let newSquare:Square = {color: "white", area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

在编译时,类型检查器允许在类型为any的参数(myObj)之下的

作为参数传递. JS代码在运行时使用鸭子类型.

below argument(myObj) inferred as type any is allowed to pass as argument by type checker at compile time. JS code use duck typing at runtime.

let myObj = {colour: 'red', width: 100};

let mySquare = createSquare(myObj);

在第二种情况下,不允许在编译时通过类型检查器传递以下自变量(SquareConfig类型除外).如手册中所述:对象文字在分配给其他变量或作为参数传递时会受到特殊对待,并进行过多的属性检查.

In second case, below argument(other thanSquareConfig type) is not allowed to pass by type checker at compile time. As mentioned in handbook: Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments.

let mySquare = createSquare({colour: 'red', width: 100});

在第二种情况下,过剩财产检查的目的是什么?

What is the purpose of excess property check, in second case?

推荐答案

在第二种情况下,过剩财产检查的目的是什么?

What is the purpose of excess property check, in second case?

它可以正确检测错误(在本例中显示为color的拼写错误),而不会产生过多的误报.

It correctly detects bugs (as shown in this case, the misspelling of color) without creating too many false positives.

由于该对象在其他任何地方都没有别名,因此TypeScript可以确信,多余的属性不会在代码的其他部分用于不同的目的.不能说myObj相同-我们可能只在这里检查它的.width,然后在其他地方使用它的.colour.

Because the object isn't aliased anywhere else, TypeScript can be fairly confident that the excess property isn't going to be used for a different purpose in some other part of the code. The same cannot be said of myObj - we may be inspecting it only for its .width here but then using its .colour in some other place.

这篇关于超额财产检查如何提供帮助?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆