簡體   English   中英

類型“{}”缺少類型 ts(2739) 中的以下屬性

[英]Type '{}' is missing the following properties from type ts(2739)

我有一個 function,它從rawData (來自 API)生成結構化數據

function makeData(raw:typeof rawData){
    const data:IData = {} // this line throws above error.

    const now = new Date()
    data.createdAt=now.toDateString();
    data.currentUser=raw.name;
    data.uniqueId= raw.id + now.toDateString();

    return data
}

在制作數據時,我在開始時使用了一個空的 object 並使用 IData 鍵入它,以便將 function 的返回值鍵入為IData 但如前所述,這是拋出錯誤。

interface IData {
    createdAt:string;
    currentUser:string;
    uniqueId:string;
}

用法:

const {createdAt, currentUser,uniqueId} = makeData(rawData)

我試圖完全刪除 IData 然后我收到以下錯誤。

Property 'createdAt' does not exist on type '{}'. // got the same error for other properties as well ( currentUser, uniqueId )

在完成破壞的行上出現相同的錯誤。

我現在有一個解決方法:

const data : Record<string,unknown>= {}

但這對我來說似乎並不更有說服力。

有沒有更好的方法將數據鍵入為 IData。

現場演示

如果不指定其中的數據,就不能定義IData的 const,相反,您可以這樣做

function makeData(raw: typeof rawData): IData{
    const now = new Date()
    
    return {
        createdAt: now.toDateString(),
        currentUser: raw.name,
        uniqueId: raw.id + now.toDateString()
    }
    
}

在這里,您將數據注釋為IData 它期望 object 包含所有必需的屬性。 (在這種情況下:createdAt、currentUser、uniqueId)

你可以做兩件事。

1:你可以做類型斷言。

const data = {} as IData.

2:用空值初始化 object。

const data:IData = {
  createdAt:"",
  currentUser:"",
  uniqueId:""
 }

發生這種情況是因為IData中的所有屬性都是必需的,因此如果您定義IData類型的變量,則需要為其提供值

也許您可以使用 UtilityType Partial或定義您要返回的類型

function makeData(raw: typeof rawData): IData { }

@mikrowdev 的評論是我認為的最佳解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM