javascript - 在哪里放置与类型相关的函数?

标签 javascript typescript

当你解决类似问题时,你是如何组织你的代码的? 我有一个接口(interface),它只定义了 js 对象应该是什么样子

interface Secured {
    security: string;
}

而且我还有一个函数来检查对象是否实现了我的接口(interface)

const isSecured: (x: any) => x is Secured = ......

我不知道人们在这些情况下如何构建他们的代码,但我有一个想法

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

但是我觉得这看起来不太好

最佳答案

通常代码是使用模块构建的。

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

当你从一个模块导出多个东西时,你可以对所有的东西使用命名导出:

export interface Secured {
    security: string;
}

export const isSecured: (x: any) => x is Secured = ......

然后,当从该模块导入时,您可以使用命名空间导入在您选择的命名空间中使用 SecuredisSecured:

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)) {
}

关于javascript - 在哪里放置与类型相关的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51700586/

相关文章:

javascript - 选择器 "app"没有匹配任何元素

javascript - 如何在 window.onscroll 事件期间只调用一次 javascript 函数?

javascript - 未定义=真;然后回到未定义?

reactjs - 是否有用于弹性属性(例如align-items和justify-content)的内置接口(interface)?

javascript - 使用javascript点击重复表单

javascript - 通过 Angular 2 中的所有组件加载脚本

typescript - 从 TypeScript 中的类读取属性名称?

javascript - Gatsby 站点的 Webpack v5 polyfill 错误

javascript - 我在我的 ul 中添加了一个 li,虽然它有效,但会导致错误

javascript - 鼠标悬停时显示/隐藏 DIV 容器