【问题标题】:I want to init mikroConfig to MikroORM with typescript and i got this error message我想用 typescript 将 mikroConfig 初始化为 MikroORM,我收到了这个错误消息
【发布时间】:2021-06-24 02:09:15
【问题描述】:

错误信息:

类型参数 '{ 只读实体:只读 [typeof Post];只读数据库名称:“lireddit”;只读类型:“postgresql”;只读调试:布尔值; }' 不可分配给“配置”类型的参数 |选项 |不明确的'。 类型'{只读实体:只读[typeof Post];只读数据库名称:“lireddit”;只读类型:“postgresql”;只读调试:布尔值; }' 不可分配给类型 'Options'。 类型'{只读实体:只读[typeof Post];只读数据库名称:“lireddit”;只读类型:“postgresql”;只读调试:布尔值; }' 不可分配给类型 'Partial>'。 属性“实体”的类型不兼容。 'readonly [typeof Post]' 类型是 'readonly' 并且不能分配给可变类型 '(string | EntityClass | EntityClassGroup | EntitySchema)[]'.ts(2345)

index.ts:

import { MikroORM } from '@mikro-orm/core';
import { __prod__ } from './constants';
import { Post } from './entities/Post';
import mikroConfig from './mikro-orm.config';

const main = async() => {
    const orm = await MikroORM.init(mikroConfig);
    const post = orm.em.create(Post, {title:'ez az első posztom hehe'})
    await orm.em.persistAndFlush(post)
}

main().catch((err) => {
    console.error(err)
})

还有 mikro-orm.config.ts:

import { Post } from "./entities/Post";
import { __prod__ } from "./constants";

export default {
    entities:[Post],
    dbName: "lireddit",
    type: "postgresql",
    debug : !__prod__,
} as const;

谢谢你的帮助,太痛苦了

【问题讨论】:

  • 来自 Ben Awad 的“全栈 React GraphQL TypeScript 教程”。 youtu.be/I6ypD7qv3Z8?t=1499 谢谢你的发帖——我也被这个绊倒了。

标签: typescript typescript-typings mikro-orm


【解决方案1】:

您定义 ORM 配置的方式是错误的,您应该使用核心包中的 Options 类型而不是 const 断言。以这种方式定义配置以获得最佳的智能感知支持(以及摆脱 TS 错误):

import { Options } from '@mikro-orm/core';
import { Post } from "./entities/Post";
import { __prod__ } from "./constants";

const config: Options = {
    entities: [Post],
    dbName: "lireddit",
    type: "postgresql",
    debug : !__prod__,
};
export default config;

【讨论】:

  • 我试试这个,但我无法获得接受 const 的“作为参数”扩展的语法:例如在 import { Options, MikroOrm } from '@mikro-orm/core';从“./entities/Post”导入{ Post }; const config: Options = { entity: [Post], dbName: "testlireddit", type: "postgresql", debug: process.env.NODE_ENV !== 'production' } as Parameters;导出默认配置;
  • 当我以这种方式定义 const 时也会出现错误。反馈是:类型“未知”不可分配给类型“选项>”。类型 'unknown' 不可分配给类型 'Pick>, "type" | “司机” | “命名策略” | “隐式交易” | “时区” | "useBatchInserts" | "useBatchUpdates" | ... 12 更多 ... | "multipleStatements">'
  • 您不应使用as constas Parameters。你真的在尝试我的回答吗?这些都不存在。您只需要输入Options
  • 谢谢,Ben 的 lireddit 教程解释了参数标签的好处
  • 我的回答告诉你应该怎么做。我是 ORM 的作者,所以我希望我比 Ben 更了解,他的教程实际上对库造成了很大的伤害,因为他没有完全理解它的很多概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2020-12-05
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多