[英]TypeScript: API alway return empty with object { [key: string]: any }
當來自 API 的響應數據始終為空時,我遇到了問題。 下面的示例代碼:
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: []
}
我不知道為什么。 有沒有人遇到過這種情況,如何處理? 請告訴我。 謝謝你。
您應該將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'}
因此,在您的代碼中,請執行以下操作:
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.