我定義了以下型別:
export type Property =
| BooleanProperty
| NumberProperty
| IntegerProperty
| StringProperty
| ObjectProperty
| ArrayProperty;
export interface OneOf {
oneOf: PropertyOrKeyword[];
}
export interface AnyOf {
anyOf: PropertyOrKeyword[];
}
type Keyword = OneOf | AnyOf;
export type PropertyOrKeyword = Property | Keyword;
在我的代碼中,我有這個:
const val = parent[objName]; // This is a PropertyOrKeyword type
if ("oneOf" in parent[objName]) {
const index = val.oneOf.findIndex(
(obj: Property) => obj.title === title
);
val.oneOf[index] = ref(title);
}
但是,當我將滑鼠懸停在 上val.oneOf時,我看到以下錯誤:
Property 'oneOf' does not exist on type 'PropertyOrKeyword'.
Property 'oneOf' does not exist on type 'BooleanProperty'.
似乎可能有太多型別被聯合起來,而 TypeScript 無法檢測到這oneOf是其中一種型別的欄位?還是我在這里做一些奇怪的事情?在我看來,這應該可以作業,并且該in短語應該有助于 TypeScript 發現val該OneOf型別。
我在這里錯過了什么嗎?它與型別的遞回性質有關嗎?
uj5u.com熱心網友回復:
TypeScript 無法理解val并且parent[objName]是同一個物件,即使分配在檢查之前的行。您應該直接檢查該val屬性。
const val = parent[objName]; // This is a PropertyOrKeyword type
if (typeof val === "object" && "oneOf" in val) {
const index = val.oneOf.findIndex(
(obj: Property) => (obj as ({title: string})).title === title
);
val.oneOf[index] = ref(title);
}
這是一個完整的TS Playground解決您的代碼。
附帶說明一下,在比較回呼中的屬性值之前,您還應該檢查是否obj具有 title 屬性或將其轉換為有點像{ title: string }titlefindByIndex
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484026.html
標籤:打字稿
