如果隐藏了 TypeScript 中的全局对象,我该如何访问它?
How do I access a global object in TypeScript if it is concealed?
假设我们有以下 TypeScript 代码:
namespace Utils.Date {
export fromInternal = (dateString: string): Date => {
const year = parseInt(dateString.substr(0, 4), 10);
const month = parseInt(dateString.substr(4, 2), 10) - 1;
const day = parseInt(dateString.substr(6, 2), 10);
return new Date(year, month, day); // error TS2351
}
}
这会导致 error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature
,因为命名空间 Utils.Date
现在隐藏了内置的 Date 构造函数。
我知道我可以使用 window.Date
在浏览器中访问 Date 构造函数,但是当我尝试在 TypeScript 中这样做时,我得到 error TS2339: Property 'Date' does not exist on type 'Window'
。相反,我将不得不使用 window['Date']
之类的东西,但那样我就会失去类型安全性。
有没有一种方法可以在不更改命名空间的情况下访问 Date 构造函数并且仍然是类型安全的?或者隐藏全局对象只是不好的做法?即便如此,我还是很想知道 是否会 是一种方式。
我的首选解决方案是避免名称冲突,尤其是在您的代码与冲突名称密切相关的情况下。名称冲突最终会影响您添加到 Utils
命名空间的更多内容。
namespace Utils.DateParsers {
但是如果您决定保持名称冲突,您可以将 Date
对象填充到一个中间变量中。
const outerDate = Date;
namespace Utils.Date {
const fromInternal = (dateString: string): Date => {
const year = parseInt(dateString.substr(0, 4), 10);
const month = parseInt(dateString.substr(4, 2), 10) - 1;
const day = parseInt(dateString.substr(6, 2), 10);
return new outerDate(year, month, day); // error TS2351
}
}
假设我们有以下 TypeScript 代码:
namespace Utils.Date {
export fromInternal = (dateString: string): Date => {
const year = parseInt(dateString.substr(0, 4), 10);
const month = parseInt(dateString.substr(4, 2), 10) - 1;
const day = parseInt(dateString.substr(6, 2), 10);
return new Date(year, month, day); // error TS2351
}
}
这会导致 error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature
,因为命名空间 Utils.Date
现在隐藏了内置的 Date 构造函数。
我知道我可以使用 window.Date
在浏览器中访问 Date 构造函数,但是当我尝试在 TypeScript 中这样做时,我得到 error TS2339: Property 'Date' does not exist on type 'Window'
。相反,我将不得不使用 window['Date']
之类的东西,但那样我就会失去类型安全性。
有没有一种方法可以在不更改命名空间的情况下访问 Date 构造函数并且仍然是类型安全的?或者隐藏全局对象只是不好的做法?即便如此,我还是很想知道 是否会 是一种方式。
我的首选解决方案是避免名称冲突,尤其是在您的代码与冲突名称密切相关的情况下。名称冲突最终会影响您添加到 Utils
命名空间的更多内容。
namespace Utils.DateParsers {
但是如果您决定保持名称冲突,您可以将 Date
对象填充到一个中间变量中。
const outerDate = Date;
namespace Utils.Date {
const fromInternal = (dateString: string): Date => {
const year = parseInt(dateString.substr(0, 4), 10);
const month = parseInt(dateString.substr(4, 2), 10) - 1;
const day = parseInt(dateString.substr(6, 2), 10);
return new outerDate(year, month, day); // error TS2351
}
}