gpt4 book ai didi

TypeScript 在传播后丢失类型信息?

转载 作者:行者123 更新时间:2023-12-05 05:07:06 25 4
gpt4 key购买 nike

<分区>

在下面的代码中,为什么 personInvalidAndErrorCaught 赋值给出了 TypeScript 错误(如我所料)而 personInvalidButErrorUncaught 却没有?特别是因为这两行都转换为相同的 JavaScript?

typescript :

interface Person {
name: string;
}
const person: Person = { name: "name" }
const personInvalidAndErrorCaught: Person = { ...person, invalidKey: "" } // Error as expected: Object literal may only specify known properties, and 'invalidKey' does not exist in type 'Person'.(2322)
const personInvalidButErrorUncaught: Person = { ...person, ...{ invalidKey: "" } } // Why no error? Especially since this line transpiles to the same JS as the line above?

转译的 JavaScript:

"use strict";
const person = { name: "name" };
const personInvalidButCaught = Object.assign(Object.assign({}, person), { invalidKey: "" });
const personInvalidButUncaught = Object.assign(Object.assign({}, person), { invalidKey: "" });

图片显示错误:

Screenshot of playground showing error

Playground Link

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