【问题标题】:Type '{}' is missing the following properties from type ts(2739)类型 \'{}\' 缺少类型 ts(2739) 中的以下属性
【发布时间】:2022-11-21 00:01:02
【问题描述】:

我有一个函数可以从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
}

当我制作数据时,我在开始时使用了一个空对象并用 IData 键入它,以便函数的返回值被键入为 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。

直播Demo

【问题讨论】:

    标签: javascript reactjs typescript compiler-errors


    【解决方案1】:

    你不能定义 IData 的常量而不指定其中的数据,相反你可以做这样的事情

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

    【讨论】:

      【解决方案2】:

      在这里,您将数据注释为 IData。它期望对象包含所有必需的属性。 (在这种情况下:createdAt、currentUser、uniqueId)

      你可以做两件事。

      1:你可以做类型断言。

      const data = {} as IData.
      

      2:用空值初始化对象。

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

      【讨论】:

        【解决方案3】:

        需要定义对象的属性

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

        并为方法添加返回类型

        makeData(raw:typeof rawData): IData { ...
        

        【讨论】:

          【解决方案4】:

          发生这种情况是因为里面的所有属性数据是必需的,所以如果你定义一个类型的变量数据你需要给它提供值

          也许你可以使用 UtilityType部分的或者定义你要返回什么类型

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

          @mikrowdev 的评论是我认为的最佳解决方案。

          【讨论】:

            猜你喜欢
            • 2019-06-21
            • 2020-12-31
            • 1970-01-01
            • 2020-09-12
            • 2021-04-02
            • 2021-04-20
            • 2021-07-29
            • 1970-01-01
            • 2020-10-28
            相关资源
            最近更新 更多