![](/img/trans.png)
[英]Using TypeScript, and Object.assign gives me an error “property 'assign' does not exist on type 'ObjectConstructor'”
[英]Typescript does assign to an object properties that do not exist in the object type definition
我不明白為什么 Typescript 沒有將此突出顯示為錯誤...
當我有條件地向 object 添加 object 類型定義中不存在的新屬性時,Typescript 會分配它
type Filters = {
keywords: Array<string>
}
const condition = 1;
let filters: Filters = {keywords: ['keyword']}
filters = {
...filters,
...(condition && {...{ tags: ['tag']}}),
}
結果:
filters: {
keywords:["keyword"]
tags:["tag"]
}
雖然我預計會收到此錯誤:
Object literal may only specify known properties, and 'tags' does not exist in type 'Filters'.
PS:當我嘗試以這種方式添加相同的屬性時,我得到了預期的錯誤:
filters = {...filters, tags: ['tag']}
這是目前 TypeScript 缺少的功能; 過多的屬性檢查只發生在特定的上下文中,到目前為止,還沒有人對傳播到外部對象中的內聯對象的內容進行上下文檢查。
在microsoft/TypeScript#39998有一個開放的功能請求。 它目前被標記為“等待更多反饋”,因此您可能需要 go 解決該問題,給它一個,並在評論中描述您的用例及其引人注目的原因。 我懷疑采取這樣的行動會產生很大的影響,但不會造成傷害。
據我所知,沒有很好的解決方法可以為您提供這種行為。 如果你想使用助手 function 之類的
const noExcess = <T extends object>() =>
<U extends { [K in keyof U]: K extends keyof T ? T[K] : never }>(u: U) => u;
並將其專門用於Filters
:
const noExcessFilters = noExcess<Filters>();
然后調用它:
const z = noExcessFilters({
...filters,
...(condition && { tags: ['tag'] }),
}); // error! Types of property 'tags' are incompatible.
它會標記這樣的情況,但我不知道這對你來說是否值得。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.