[英]TypeScript: API alway return empty with object { [key: string]: any }
I have issue when response data from API alway empty.当来自 API 的响应数据始终为空时,我遇到了问题。 Sample code below:
下面的示例代码:
interface DataStore {
[key: string]: any,
}
static GetData = async (req: Request, res: Response): Promise<Response> => {
let obj: DataStore = [];
obj['id'] = 'account';
obj['pwd'] = 'password';
console.log(obj); // can see data: [ id: 'account', pwd: 'password' ]
res.status(200).send(obj); // it return empty: []
}
I don't know why.我不知道为什么。 Has anyone encountered this, and how to handle it?
有没有人遇到过这种情况,如何处理? Please let me know.
请告诉我。 Thank you.
谢谢你。
You should set your obj
to an empty object {}
:您应该将
obj
设置为空的 object {}
:
const t1 = [] t1['foo'] = 'foo' t1['bar'] = 'bar' console.log(JSON.stringify(t1)) // [] const t2 = {} t2['foo'] = 'foo' t2['bar'] = 'bar' console.log(JSON.stringify(t2)) // {foo: 'foo', bar: 'bar'}
So, in your code, do the following:因此,在您的代码中,请执行以下操作:
interface DataStore {
id?: string,
pwd?: string,
}
// No need for `async` here since there is no `async` code here
static GetData = (req: Request, res: Response): void => {
const obj: DataStore = {};
obj['id'] = 'account';
obj['pwd'] = 'password';
res.status(200).json(obj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.