何时使用声明模块和声明名称空间

时间:2020-08-27 00:20:20

标签: typescript

我是going through one of the repo的人,他们是如何看待ts回购交易的。

我仔细看了看他们的打字

/**
 * react-native-extensions.d.ts
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT license.
 *
 * Type definition file that extends the public React Native type definition file.
 */

    import * as React from 'react';
    import * as RN from 'react-native';
    import * as RNW from 'react-native-windows';
    
    declare module 'react-native' {
        interface ExtendedViewProps extends RN.ViewProps

 {

现在,我无法确定何时应使用declare moduledeclare namespace?我能在stackoverflow上碰到最接近的this answer,但是我认为这共享了两者之间的区别,而不是何时使用它们(以及使用哪个)

打字稿手册说明了这一点

这篇文章概述了使用TypeScrip中的模块和名称空间组织代码的各种方式

我无法理解上面的定义。

1 个答案:

答案 0 :(得分:0)

根据我的经验,declare moduledeclare namespaceDeclaration Merging的上下文中最有用。基本上,由于在Javascript中,您可以猴子类的原型或向第三方类添加属性,因此声明合并为您提供了一种方式,可以将这些动态变化暴露给类型系统中对象的行为。

例如,考虑express.js中的Request对象。 express公开的API不会公开请求ID的字段。但是,在javascript中,习惯上是简单地对请求对象进行突变。

middlware(req, res, next) {
  req.id = uuid.v4()
  next()
}

Typescript不喜欢这样,因为对于普通的快速类型定义,id不是请求的属性。您可以使用declare module和这样的声明进行修复:

import { Request } from "express";
import core from "express-serve-static-core";

declare module "express" {
  interface Request<
    P extends core.Params = core.ParamsDictionary,
    ResBody = any,
    ReqBody = any,
    ReqQuery = core.Query
  > {
    /**
     * An optional request id that can be attached to the request. Useful for correlating
     * and searching log messages.
     */
    id?: string;
  }
}

如果您将此文件包含在类型路径中,Typescript将很乐意接受Request的可选id属性。 declare namespace的用例类似。