TypeScript,无索引签名,参数类型为“字符串”

时间:2020-11-12 16:50:48

标签: javascript typescript

我正在尝试使用数组中编写的一些字段排序规则来排序对象:

这是订购规则:

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

这是需要订购的对象:

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

所以我的想法是这样做:

const feeLookupRequest = {};

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

它可以正常工作,我可以制作一个显示以下内容的console.log(feeLookupRequest)

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

但是我遇到了一些我不太了解的类型错误:

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 '{}'.

有任何提示吗?

编辑:实际上,如果我发送的agentSequence: false对象feeLookupRequest不具有agentSequence属性,我不知道该如何管理。

测试代码:

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

2 个答案:

答案 0 :(得分:0)

首先,您不应该期望对象上的键有特定顺序。这就是为什么对它们进行排序不是一个最佳主意的原因。

从错误开始,您应该指出requestfeeLookupRequest都有索引

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
    }
}

答案 1 :(得分:0)

您可能必须为文字对象定义一些类型以使其正常工作,因为tsc会根据您给定的值推断类型:


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];
  }
}