网站搜索

typescript - TSLint 提示 Expression is always true. (strict-type-predicates) 对 typeof document !== 'undefined'


在 tsconfig.json 中启用 strictNullChecks 后,我现在在 typeof document !== 'undefined' 上收到了 TSLint says Expression is always true.(strict-type-predicates)

有没有办法在不使用 tslint:disable-next-line: strict-type-predicates 来静音它的情况下纠正这个问题?

我假设问题是由 lib.dom.ts 中这一行引起的,它没有联合类型 | null。declare var document: Document;

我正在做服务器端渲染,所以 window 和 document 可能不存在。

答案#1

我正在做一个 SSR 项目,我使用了 'as' 操作符来绕过针对 window 对象的这个 lint 规则,它对 document 也同样有效。

const isBrowser = typeof (window as any) !== 'undefined'

export default isBrowser