【发布时间】:2020-08-20 18:10:01
【问题描述】:
我有类似的东西:
const request: Partial<Request> = {
method,
cache,
redirect,
headers: {} as Headers,
};
if (...) {
request.headers['content-type'] = contentType;
}
但是,TS 抱怨Object is possibly 'undefined'.,可能是因为Partial。
如果我不包括Partial<>,我会得到:
Type '{ method: string; cache: RequestCache; redirect: RequestRedirect; headers: Headers; }' is missing the following properties from type 'Request': credentials, destination, integrity, isHistoryNavigation, and 15 more.
为什么 TS 不能推断 headers 已经定义?
【问题讨论】:
-
你的情况如何?
-
它会检查它是否不是 GET 请求以及
contentType是否真实。 -
两个观察结果:1) 应该使用
get()方法而不是索引签名来访问标头值2) 您仍然可以这样做使用Partial<Request>,您需要告诉 TS 编译器您确定headers使用非空断言运算符(例如request.headers!.get('content-type'))是非空的。
标签: javascript typescript