TypeScript可选对象键行为不正常

问题描述 投票:4回答:2

我有一个带有条件键的对象。即:

const headers: RequestHeaders = {};

if (...) {
  headers.foo = 'foo';
}

if (...) {
  headers.bar = 'bar';
}

我是TS的新手,我希望它能正常工作:

type RequestHeaders = {
  foo?: string,
  bar?: string,
};

但是,我将其传递给fetchfetch标头的类型定义为{ [key: string]: string }。我得到:

Type 'RequestHeaders' is not assignable to type '{ [key: string]: string; }'.
  Property 'foo' is incompatible with index signature.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.

我可以使它起作用的唯一方法是type RequestHeaders = { [key: string]: string };。有没有一种方法可以将键限制为一组预定义的字符串?

javascript typescript
2个回答
0
投票

首先,您不应将初始值设置为某个常数,然后尝试对其进行更改。

这里有一个示例可以满足您的要求:

type RequestHeaders = {
  'foo': string,
} | {
  'bar': string,
} | {}

type FetchResult = {
  [key: string]: string;
}

let headers: RequestHeaders = {};
const i = 2
if (i % 1) {
  headers = { 'foo': 'yes' };
} else {
  headers = { 'bar': 'yes' };
}

const fetchResult: FetchResult = headers;

这正在Typescript Playground上生成此javascript:

"use strict";
let headers = {};
const i = 2;
if (i % 1) {
    headers = { 'foo': 'yes' };
}
else {
    headers = { 'bar': 'yes' };
}
const fetchResult = headers;


0
投票

获取headers类型正在告诉您一些信息。它不接受具有不确定值的对象。您的每个可选类型都可以是string | undefined,因此编译器会拒绝它。您可以根据自己的风格采取多种方法。这是一种可能适合您的方法。

const headers: RequestHeaders = {};

type RequestHeaders = {
  foo?: string;
  bar?: string;
};

// Remove keys with undefined values.
const buildHeaders = (requestHeaders: RequestHeaders): HeadersInit =>
  Object.entries(requestHeaders).filter(
    (entry): entry is [string, string] => entry[1] !== undefined
  );

fetch("Some Data", {
  headers: buildHeaders(headers)
});
© www.soinside.com 2019 - 2024. All rights reserved.