【问题标题】:convert object into interface Object typescipt将对象转换为接口对象打字稿
【发布时间】:2021-07-24 12:47:49
【问题描述】:

我是打字稿的新手,正在做一个项目。 我正在尝试构建一个 REST API,并且我的请求有效负载有一个模型。

但是在类型转换之后 reObj 的类型仍然是对象,我希望它是 requestObj 类型

 export const funcName = async function (req: Express.Request, res: Express.Response) {

        console.log(typeof req.body)  // object
        const resObj : requestObj  =  req.body as requestObj 
        console.log(typeof resObj)  // object.     but it should be requestObj

export interface requestObj {
    to:  string ,
    name: string,
    phoneNo : string, 
}

因为这些数据根本没有得到验证。 我搜索了很多,但找不到任何灵魂。

【问题讨论】:

标签: node.js typescript rest express backend


【解决方案1】:

TypeScript 被编译成 JavaScript 文件,并且 JavaScript 没有任何名为 requestObj 的类型。所有对象的类型为object。在 TypeScript 中,所有类型都只在编译之前存在。如果你想检查 TypeScript 中的类型,你应该使用conditional types,因为使用 javascript 的 'typeof' 对你没有帮助。

【讨论】:

  • requestObj 是接口的名称,不是任何类型。如果可以的话,我想要将 obkect 转换为任何接口类型。
猜你喜欢
  • 2018-10-10
  • 1970-01-01
  • 2021-06-03
  • 2020-12-15
  • 2017-03-22
  • 1970-01-01
  • 2017-02-11
  • 2016-10-05
  • 2018-06-07
相关资源
最近更新 更多