如何在打字稿中定义类型为“ set-cookie”为“ string []”但其他键为“ string”的类型?

时间:2020-05-10 00:27:12

标签: typescript typescript-typings

我想定义一个类似于响应标头的类型,

type Headers = { [key: string]: string }

但是,如果键为set-cookie,则其类型应为string[]

我尝试了

type Headers = { 'set-cookie'?: string[] } & { [key: string]: string };

但要输入代码:

const headers: H = {
  'set-cookie': ['cookie'],
  'aaa': '111'
}

它具有编译错误:

TS2322: Type '{ 'set-cookie': string[]; aaa: string; }' is not assignable to type 'Headers'.   
Type '{ 'set-cookie': string[]; aaa: string; }' is not assignable to type '{ [key: string]: string; }'.     
Property ''set-cookie'' is incompatible with index signature.       
Type 'string[]' is not assignable to type 'string'.

是否可以定义这种类型?

1 个答案:

答案 0 :(得分:0)

您的.flatMap类型应该是两种类型的交集。

return

func downloadUserProfilePhoto(user: User) -> AnyPublisher<UIImage?, StoreError> { guard let url = user.imageURL.flatMap({ URL(string: $0) }) else { return Result.Publisher(nil).eraseToAnyPublisher() } return NetworkService.getData(url: url) .mapError { _ in .cantDownloadProfileImage } .flatMap({ data in UIImage(data: data) .map { Result.Publisher($0) } ?? Result.Publisher(.cantDownloadProfileImage) }) .eraseToAnyPublisher() } 键定义为类型Headers,也是可选的类型(interface CookieHeader {'set-cookie'?: string[]; } ,因为您的set-cookie对象可能不具有此属性。

第二个定义要复杂得多

string[]

这实际上是在定义?键而没有Headers键的接口。
看看Typescript utility types

然后,type CommonHeaders = { [key: string]: string } & { 'set-cookie'?: never }; 类型定义很简单

string

希望有帮助。

相关问题