gpt4 book ai didi

typescript - 在类型检查中传递命名对象和匿名对象之间的差异

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:41 24 4
gpt4 key购买 nike

考虑以下代码

interface Config {
label?: string;
width?: number;
}

function printLabel(labelledObj: Config) {
console.log(labelledObj.label);
}

let myObj = {not_in_interface: 10, label: "Size 10 Object"};

// No error
printLabel(myObj);

// Will run into error Argument of type '{ not_in_interface: number; label: string; }' is not assignable to parameter of type 'Config'
printLabel({not_in_interface: 10, label: "Size 10 Object"});

差异的原因是什么?

似乎匿名对象会触发过多的属性检查,而命名对象不会。

最佳答案

TypeScript 仅在声明对象文字的位置检查多余的属性(如您在问题中所述)。 The TypeScript docs describe this check :(也可以随时查看 full spec here。)

TypeScript 1.6 enforces stricter object literal assignment checks for the purpose of catching excess or misspelled properties. Specifically, when a fresh object literal is assigned to a variable or passed as an argument for a non-empty target type, it is an error for the object literal to specify properties that don't exist in the target type.

那么为什么会有这种行为呢?简而言之,在某些用例中,您希望在传递对象时允许额外的属性,而在其他用例中则不允许。例如,如果我们下面的 printWeightInPounds 函数不接受我们的 Dog 对象,那就太遗憾了:

interface Animal { weight: number; }
interface Dog extends Animal { breed: string; }

const myDog: Dog = { weight: 100, breed: "Poodle" }; // a big poodle!
printWeightInPounds(myDog);

在所有情况下都严格且不允许额外的属性将不允许许多合法代码。但是,在某些地方,选择加入严格性可能是一件好事。有人提议拥有“精确类型”功能,允许您选择只传递相同的类型。还是in discussion尽管。

关于typescript - 在类型检查中传递命名对象和匿名对象之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47539851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com