我是经过一次回购,是为了看看人们是如何构造他们的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 module或declare namespace?我在堆栈溢出时遇到的最接近的这个答案,但我认为这与两者的区别是相同的,而不是什么时候使用它们(以及使用哪一个)。
打字本手册规定如下:
本文概述了使用TypeScrip中的模块和命名空间组织代码的各种方法
我无法理解上面的定义。
发布于 2020-08-27 02:40:14
根据我的经验,declare module和declare namespace在声明合并上下文中非常有用。基本上,因为在Javascript中,您可以对类的原型进行修改或向第三方类添加属性,因此声明合并为您提供了一种将这些动态更改公开给类型系统中的对象行为的方法。
例如,考虑来自express.js的express.js对象。express公开的API不公开类似请求id的字段。然而,在javascript中,简单地更改请求对象是惯例。
middlware(req, res, next) {
req.id = uuid.v4()
next()
}但是,类型记录不喜欢这样,因为使用普通的表达式类型定义,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;
}
}如果在类型路径中包含此文件,类型记录将乐于接受请求的可选id属性。declare namespace的用例类似。
https://stackoverflow.com/questions/63607441
复制相似问题