我正在使用MobX,并且该存储库包含我的应用程序中的所有实体。
我想拥有两个功能
但是我也希望它们是类型安全的。
假设我保留此收藏集:
@observable entities = {
authors: {} as Record<string, Author>,
comments: {} as Record<string, Comment>,
posts: {} as Record<string, Post>
}
我想像下面这样使用我的函数:
// "authors" should be checked against "authors" | "posts" | "comments"
// by specifying "authors" statically, I want typescript to automatically refine the return type to be Author, otherwise Author | Posts | Comment
addEntity("authors", new Author(...))
// same here
getEntity("authors", id)
我已经尝试了很多使用泛型的方法,但是我做不到。 我必须添加类型转换为的通用类型 所以我的电话是这样的:
getEntity<Author>("authors")
// but nothing prevents me from writing
getEntity<Author>("posts")
有一个技巧可以使这项工作成功吗?
答案 0 :(得分:0)
不确定MobX部分,但打字稿类型是索引类型查询和keyof
的直接应用:
class Author { id!: string; a!: string }
class Comment { id!: string; c!: string }
class Post {id!: string; p!: string }
class Store {
entities = {
authors: {} as Record<string, Author>,
comments: {} as Record<string, Comment>,
posts: {} as Record<string, Post>
}
}
let store = new Store();
function addEntity<K extends keyof Store['entities']>(type: K, value: Store['entities'][K][string]) {
let collection = store.entities[type] as Record<string, typeof value>; // some type assertions required
collection[value.id] = value;
}
function getEntity<K extends keyof Store['entities']>(type: K, id: string): Store['entities'][K][string] {
let collection = store.entities[type] as Record<string, Store['entities'][K][string]>; // some type assertions required
return collection[id];
}
addEntity("authors", new Author())
addEntity("authors", new Post()) // err
// same here
let a: Author = getEntity("authors", "1")
let p : Post = getEntity("authors", "1") //err