嗨,我是 Typescript 的新手,我有一个对象类型变量,其中可能有来自不同类型或嵌套对象的不同值。现在我的问题是,如何为该对象定义一个模型,以便在调用不同的键时不会遇到示例错误?
例如:
export class Controller {
protected static response(res: Response, statusCode: number = 200, data: any, user: string = '', dev: string = '', code: number = 200, result: string = 'success'){
res.status(statusCode).send({
data: data,
message: {
user: '',
dev: ''
},
code: 403,
result: 'Error'
})
}
ERROR: res.status ---> This expression is not callable. Type 'Number' has no call signatures
我也遇到了这个错误,并意识到我只是忘记导入 Response。添加导入行解决了我的问题。
import express, {Request, Response} from 'express';
在 NextJS 中确保导入正确的响应类型。
import { NextApiResponse } from "next";
如果它对其他人有帮助,我在这样的情况下也看到了同样的错误:
const shift = progressWidth * percentage
(this.$refs.expected as Vue).$el.style.left = "100px"
其中
percentage
是 number
。发生错误是因为没有分号,第二行被解释为该行的一部分,如下所示:
const shift = progressWidth * percentage(this.$refs.expected as Vue).$el.style.left = "100px"
这可以通过添加前导分号来解决:
const shift = progressWidth * percentage
;(this.$refs.expected as Vue).$el.style.left = "100px"
或者更好的是,重新排列,这样就根本不需要它了:
const expected = (this.$refs.expected as Vue).$el
const shift = progressWidth * percentage
expected.$el.style.left = "100px"
在您的控制器中,只需导入来自
express
或您使用的框架的响应即可工作。
import { Response } from 'express';
res.status
是根据该错误消息的数字。看起来控制器没有被使用正确的参数调用。 console.log(res)
在致电 res.status
之前检查您的呼叫站点代码。
首先添加这一行即可获得NEXTJS中express的所有功能。请记住,您添加了这一行,而不是本页中提到的其他行。
import { NextApiRequest, NextApiResponse } from "next";
// This function handle the POST request and defeat all your errors.
import { NextApiRequest, NextApiResponse } from "next";
// You must have to mention the type of handle function's parameter which we already
//get from next package (NextApiRequest, NextApiResponse).
//NOTE:- You can change the function name, that's your choice
export default function handle(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
res.status(405)
}
}
使用
(res as any).status(statusCode).send({data: data, message:{user: '',dev: ''},code: 403,result: 'Error'})
对于任何打字稿库/框架,如果您使用像express、nestjs这样的