我想扩展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类 - …
我已经在 .d.ts 中声明了命名空间,它应该是全局可用的,如下所示:
/src/typings/content.d.ts
import * as something from 'something';
declare namespace Content {
...
type Object = internal.Object;
}
Run Code Online (Sandbox Code Playgroud)
我想将此命名空间用于 TSX 文件中的接口:
import * as React from 'react';
interface ExampleComponentProps {
example: Content.Object;
}
export const ExampleComponent: React.FunctionComponent<ExampleComponentProps> = ({ example }) => {
return <div>{example}</div>;
};
Run Code Online (Sandbox Code Playgroud)
打字稿现在告诉我:Cannot find namespace 'Content'。
我的 tsconfig 看起来像这样:
{
"compilerOptions": {
// General settings for code interpretation
"target": "esnext",
"module": "commonjs",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"noEmit": true,
"noEmitOnError": true, …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Typescript 中使用 globalThis,我想就如何以更好的方式编写它提出一些建议。
目前的实现是这样的:
创建一个文件types/global.d.ts并在里面添加
interface Global {
foo: string
}
declare let foo: Global["foo"];
Run Code Online (Sandbox Code Playgroud)
在tsconfig.json添加
"files": [
"types/global.d.ts"
]
Run Code Online (Sandbox Code Playgroud)
然后,以设定的值foo使用
(globalThis as any).foo = "The value of foo"
Run Code Online (Sandbox Code Playgroud)
我不喜欢这种方法首先是需要样板(但我认为这是无法避免的),其次是(globalThis as any).foo =表达式