Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将与类型相关的函数放在何处?_Javascript_Typescript - Fatal编程技术网

Javascript 将与类型相关的函数放在何处?

Javascript 将与类型相关的函数放在何处?,javascript,typescript,Javascript,Typescript,当您解决类似的问题时,您如何构造代码? 我有一个接口,它只定义js对象应该是什么样子 interface Secured { security: string; } 我还有一个函数,检查对象是否实现了我的接口 const isSecured: (x: any) => x is Secured = ...... 我不知道人们在这种情况下是如何构造代码的,但我有一个想法 class Secured { static Type = interface...... st

当您解决类似的问题时,您如何构造代码? 我有一个接口,它只定义js对象应该是什么样子

interface Secured {
    security: string;
}
我还有一个函数,检查对象是否实现了我的接口

const isSecured: (x: any) => x is Secured = ......
我不知道人们在这种情况下是如何构造代码的,但我有一个想法

class Secured {
    static Type = interface......
    static isSecured = .....
}

但是这看起来不太好,我认为通常代码是使用模块构建的

看起来
Secured
isSecured
总是要一起使用,所以使用它们似乎很自然 将它们放在一个模块中,例如在
secured.ts

从模块导出多个内容时,可以对所有内容使用命名导出:

export interface Secured {
    security: string;
}

export const isSecured: (x: any) => x is Secured = ......
然后,当从该模块导入时,您可以使用名称空间导入使
安全
安全
在您选择的名称空间中可用:

import * as Secured from '.../relative-path-to/secured'; 
// here we choose Secured as namespace name


let s: Secured.Secured | SomethingElse;

if (Secured.isSecured(s)) {
}
或者,您可以使用命名导入并重命名其中一些导入:

import {Secured as SecuredType, isSecured} from '.../relative-path-to/secured'; 

let s: SecuredType | SomethingElse;

if (isSecured(s)) {
}

如果您使用的是模块,我会做
导出接口安全{…
导出常量安全=…
然后在需要的地方导入它们中的任何一个。如果您没有使用模块…为什么?无论哪种方式,我觉得这个问题都更适合,因为它是基于观点的