相关疑难解决方法(0)

如何在TypeScript中的`window`上显式设置新属性?

我通过显式设置属性来为我的对象设置全局命名空间window.

window.MyNamespace = window.MyNamespace || {};
Run Code Online (Sandbox Code Playgroud)

TypeScript强调MyNamespace并抱怨:

属性'MyNamespace'在'window'类型的值上不存在任何"

我可以通过声明MyNamespace为环境变量并删除window显式来使代码工作,但我不想这样做.

declare var MyNamespace: any;

MyNamespace = MyNamespace || {};
Run Code Online (Sandbox Code Playgroud)

我怎样才能window留在那里让TypeScript开心?

作为旁注,我发现TypeScript抱怨特别有趣,因为它告诉我这种window类型any绝对可以包含任何东西.

typescript

502
推荐指数
25
解决办法
27万
查看次数

How to check if an object is a readonly array in TypeScript?

How to do an array check (like Array.isArray()) with a readonly array (ReadonlyArray)?

As an example:

type ReadonlyArrayTest = ReadonlyArray<string> | string | undefined;

let readonlyArrayTest: ReadonlyArrayTest;

if (readonlyArrayTest && !Array.isArray(readonlyArrayTest)) {
  // Here I expect `readonlyArrayTest` to be a string
  // but the TypeScript compiler thinks it's following:
  // let readonlyArrayTest: string | readonly string[]
}
Run Code Online (Sandbox Code Playgroud)

With an usual array the TypeScript compiler correctly recognises that it must be a string inside the if condition.

arrays typechecking typescript

2
推荐指数
1
解决办法
290
查看次数

标签 统计

typescript ×2

arrays ×1

typechecking ×1