我想扩展Express Session类型以允许在会话存储中使用我的自定义数据.我有一个对象req.session.user是我班级的一个实例User:
export class User {
public login: string;
public hashedPassword: string;
constructor(login?: string, password?: string) {
this.login = login || "" ;
this.hashedPassword = password ? UserHelper.hashPassword(password) : "";
}
}
Run Code Online (Sandbox Code Playgroud)
所以我创建了我的own.d.ts文件以将定义与现有的快速会话类型合并:
import { User } from "./models/user";
declare module Express {
export interface Session {
user: User;
}
}
Run Code Online (Sandbox Code Playgroud)
但它根本不起作用 - VS Code和tsc看不到它.所以我用简单的类型创建了测试定义:
declare module Express {
export interface Session {
test: string;
}
}
Run Code Online (Sandbox Code Playgroud)
并且测试字段工作正常,因此导入导致问题.
我也尝试添加/// <reference path='models/user.ts'/>导入但是tsc没有看到User类 - …
我在两个单独的文件中有两个类,一个从另一个扩展.基类包含一些import使用节点模块的语句.我不清楚为什么派生类(在一个单独的文件中)不能识别基类!!! ???
有人可以澄清一下吗?
// UtilBase.ts
/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/packages.d.ts" />
import * as path from "path"; // <---- THIS LINE BREAKS THE BUILD!!!!
namespace My.utils {
export class UtilBase {
protected fixPath(value: string): string {
return value.replace('/', path.sep);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后
// UtilOne.ts
/// <reference path="UtilBase.ts" />
namespace My.utils {
export class UtilOne extends My.utils.UtilBase {
}
}
Run Code Online (Sandbox Code Playgroud)
编译后我得到:
src/UtilOne.ts(6,47): error TS2339: Property 'UtilBase' does not
exist on type 'typeof utils'
Run Code Online (Sandbox Code Playgroud) 我有一个.d.ts直接依赖于Immutable 的环境模块:
/// <reference path="../node_modules/immutable/dist/immutable.d.ts" />
import I = require('immutable');
declare module 'morearty' {
}
Run Code Online (Sandbox Code Playgroud)
但是编译器禁止直接引用immutable:
error TS2435: Ambient external modules cannot be nested in other modules.
如何在环境模块中包含不可变环境声明?我试图从另一个代理模块导入不可变但没有运气.
我喜欢定义一个全局可用的助手
global.p = console.log.bind(console)
Run Code Online (Sandbox Code Playgroud)
所以我可以使用p('some message')代替console.log('some message').
但是 TypeScript 抱怨这p是未定义的。有没有办法告诉 TypeScript 编译器p每个文件中都有一个可用的全局变量?