当你解决类似问题时,你是如何组织你的代码的? 我有一个接口(interface),它只定义了 js 对象应该是什么样子
interface Secured {
security: string;
}
而且我还有一个函数来检查对象是否实现了我的接口(interface)
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 = ......
然后,当从该模块导入时,您可以使用命名空间导入在您选择的命名空间中使用 Secured
和 isSecured
:
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/