如何在 TypeScript 中定义全局函数? [英] How to define global function in TypeScript?

查看:71
本文介绍了如何在 TypeScript 中定义全局函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个随处可用的全局函数,使用时不需要导入模块.

I want to define a global function that is available everywhere, without the need to import the module when used.

此函数旨在替换 C# 中可用的安全导航运算符 (?).为了可读性,我不想在函数前加上模块名.

This function aims to replace the safe navigation operator (?) available in C#. For the sake of readability, I don't want to prefix the function with a module name.

Global.d.ts:

Global.d.ts:

declare function s<T>(someObject: T | null | undefined, defaultValue?: T | null | undefined) : T;

Global.tsx:

Global.tsx:

///<reference path="Global.d.ts" />

export function s<T>(object: T | null | undefined, defaultValue: T | null = null = {} as T) : T {
    if (typeof object === 'undefined' || object === null)
        return defaultValue as T;
    else
        return object;
}

App.tsx(根 TypeScript 文件):

App.tsx (root TypeScript file):

import 'Global';

其他 TSX 文件(方法用法):

Other TSX file (method usage):

s(s(nullableVar).member).member; //Runtime error

这编译得很好,但是,在浏览器中这会抛出s is not a function".

This compiles fine, however, in the browser this throws 's is not a function'.

推荐答案

您正在为编译器定义类型,但实际上并未将其附加到全局命名空间 — window 在浏览器中,<节点中的代码>全局.不要从模块中导出它,而是附加它.对于同构使用,请使用类似...

You're defining the type for the compiler, but not actually attaching it to the global namespace — window in the browser, global in node. Instead of exporting it from the module, attach it. For isomorphic use, use something like...

function s() { ... }

// must cast as any to set property on window
const _global = (window /* browser */ || global /* node */) as any
_global.s = s

您也可以放弃 .d.ts 文件并使用 declare global 在同一文件中声明类型,例如

You can also ditch the .d.ts file and declare the type in the same file using declare global, e.g.

// we must force tsc to interpret this file as a module, resolves
// "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."
// error
export {}

declare global {
  function s<T>(someObject: T | null | undefined, defaultValue?: T | null | undefined) : T;
}

const _global = (window /* browser */ || global /* node */) as any
_global.s = function<T>(object: T | null | undefined, defaultValue: T | null = null) : T {
  if (typeof object === 'undefined' || object === null)
    return defaultValue as T;
  else
    return object;
}

这篇关于如何在 TypeScript 中定义全局函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆