-1

I'm trying to order an object with some fields order rule written in an array:

This is the order rules:

const fieldsOrder = [
  'agentID',
  'agentSequence',
  'token'
];

This is the object that it needs to be ordered:

const request = {
  token: 'TEST',
  agentSequence: true,
  agentID: '40208697',
}

So my idea was to do this:

const feeLookupRequest = {};

for(const field of fieldsOrder) {
  if (request[field]) {
    feeLookupRequest[field] = request[field]; // ERROR
  }
}

And it works, and I can make a console.log(feeLookupRequest) which shows:

{
  agentID: '40208697',
  agentSequence: true,
  token: 'TEST'
}

But I'm getting some types errors that I don't understand very well:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used
to index type '{}'.   No index signature with a parameter of type 'string' was found on type '{}'.

Any hint?

EDIT: actually, if I sent agentSequence: false the feeLookupRequest object has not the agentSequence property, I don't know how could I manage that.

Code for testing:

https://jsfiddle.net/pmiranda/7n4qd12t/

pmiranda
  • 7,602
  • 14
  • 72
  • 155

2 Answers2

0

First of all you shouldn't expect a certain order of keys on an object. That's why it's not a best idea trying to sort them.

As of the error you should indicate that request and feeLookupRequest has indexes

const fieldsOrder = [
    'agentID',
    'agentSequence',
    'token'
];

const request: Record<string, any> = {
    token: 'TEST',
    agentSequence: '7',
    agentID: '40208697',
};

const feeLookupRequest: Record<string, any> = {};

for (const field of fieldsOrder) {
    if (request[field]) {
        feeLookupRequest[field] = request[field]; // ERROR
    }
}
Anatoly
  • 20,799
  • 3
  • 28
  • 42
0

You might have to define a few types for your literal object to make it work properly since tsc would infer typings based on your given values:


const request = {
  token: 'TEST',
  agentSequence: '7',
  agentID: '40208697',
};

// First define your Request type based on your literal object
type Request = typeof request;

const fieldsOrder = [
  'agentID',
  'agentSequence',
  'token'
] as (keyof Request)[]; // Each value must be a `keyof` request object type


// This is also a copy of request object so its type is Request
const feeLookupRequest = {} as Request;

// Now tsc would understand `field` is a keyof Request so it would work properly
for(const field of fieldsOrder) {
  if (request[field]) {
    feeLookupRequest[field] = request[field];
  }
}

tmhao2005
  • 14,776
  • 2
  • 37
  • 44