简体   繁体   English

无法从打字稿到达全局变量?

[英]Can't reach global variables from typescript?

I'm currently working with an mvc-project. 我目前正在使用mvc项目。 The project has been outsourced so I haven't written the code myself. 该项目已外包,所以我自己没有编写代码。

My mission is to convert one of the Javascript to a Typescript to begin with. 我的任务是首先将Javascript之一转换为Typescript。 The problem is that when I put my code in the ts-file I can't reach the global variables. 问题是,当我把我的代码放在ts文件中时,我无法访问全局变量。 Visual Studio just says that "the property does not exist on type window". Visual Studio只是说“属性在类型窗口中不存在”。

My .ts-file: 我的.ts文件:

window.location.href = window.Search.URL_Searchfiles;

Some of them are located in .cshtml files between script tags and they use razor to set the variables. 其中一些位于脚本标记之间的.cshtml文件中,它们使用razor设置变量。

The .cshtml-file: .cshtml文件:

<script>var Search = { URL_Searchfiles: '@Url.Action("Files", "Search")' }</script>

I've tried to declare the variables in the Typescript but I can't seem to get it right. 我试图在Typescript中声明变量,但我似乎无法做到正确。 How do i reach global variables from a Typescript? 如何从打字稿中获取全局变量?

You will need to extend the Window interface to add a Search element to it: 您需要扩展Window界面以向其添加Search元素:

interface Window {
    Search: any;
}

window.location.href = window.Search.URL_Searchfiles;

Interfaces in TypeScript are open-ended, so you can keep binding new members to a particular object via it's interface. TypeScript中的接口是开放式的,因此您可以继续通过其接口将新成员绑定到特定对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM