我开始使用 Nest.Js 并创建了一个具有以下结构的全栈应用程序:
api:nestjs 应用程序
client:前端应用程序
models:后端和前端之间的共享模型(仅限接口)
所以我tsconfig.json在 api 文件夹中设置了别名路径,让它很快导入:import { User } from 'models/user.model'
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"incremental": true,
"outDir": "./dist",
"baseUrl": "./",
"paths": {
"models/*": ["../models/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是打字稿正在编译和更改dist文件夹下的根结构,而 nest cli 没有找到main.js启动应用程序的文件。
有没有办法移动models文件夹并保留 nestjs 结构?或者可能更改 nestjs 配置以启动应用程序api/src/main.js?
取以下函数:
function test<T>(this: { value: T }) {
return this.value;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用call, applyorbind并提供this上下文,TypeScript 将不会推断提供的类型,并且unknown在这种情况下它将返回。
const a = test.apply({ value: 1 }); // a: unknown
const b = test.call({ value: 'b' }); // b: unknown
const fn = test.bind({ value: true }); // fn: () => unknown
Run Code Online (Sandbox Code Playgroud)
好的,这可能是因为apply,例如,被声明为apply<T, R>(this: (this: T) => R, thisArg: T): R,所以它需要您告知R返回类型。但如果你只显式声明函数的类型test,你将得到正确的类型:
const typed = (test<number>).apply({ value: 1 }); // …Run Code Online (Sandbox Code Playgroud) 我知道它太通用了,但我希望创建一个类,该类将包含这样的通用类型的所有道具和原型:
class GenericExtend<T> extends T {
constructor(data: T) {
// here is a workaround to make these 2 classes unique
const proto = { ...GenericExtend.prototype };
Object.assign(proto, Object.getPrototypeOf(data));
Object.setPrototypeOf(this, proto);
Object.assign(this, data);
}
GenericMethod() { }
}
Run Code Online (Sandbox Code Playgroud)
现在,我可以实例化GenericExtend类,然后像这样获取两个类的类型:
const obj = new GenericExtend<Model>(data);
obj.GenericMethod(); // ok
obj.ModelMethod(); // good!
Run Code Online (Sandbox Code Playgroud)
我的解决方案之一是使用交集,如下所示:
const obj: GenericExtend & Model = new GenericExtend(data) as any;
Run Code Online (Sandbox Code Playgroud)
它奏效了,但我不太喜欢。有什么我可以做的更好的事情吗?