Home > Enterprise >  TypeScript: API alway return empty with object { [key: string]: any }
TypeScript: API alway return empty with object { [key: string]: any }

Time:12-29

I have issue when response data from API alway empty. 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.

CodePudding user response:

You should set your obj to an empty 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);
}
  • Related