我试图在typescript中实现一个类似于图的数据结构,并且很困难地实现了它的类型安全,在许多解决方案之后,我得出了以下结论:
interface Cities {
lisbon: any
porto: any
faro: any
}
class Graph<T> {
adjacencyList: {
[K in keyof T]?: (keyof T)[]
} = {}
addVertex(value: keyof T) {
if (!this.adjacencyList[value]) this.adjacencyList[value] = []
}
addEdge(vertex1: keyof T, vertex2: keyof T) {
this.adjacencyList[vertex1]?.push(vertex2)
this.adjacencyList[vertex2]?.push(vertex1)
}
}有没有更优雅的方式呢?我想使用泛型,以使其更加通用。这样的事情有可能发生吗?
enum Cities {
"lisbon",
"porto",
"faro"
}
class Graph<T> {
adjacencyList: {
[K in T]?: T[]
} = {}
addVertex(value: T) {
if (!this.adjacencyList[value]) this.adjacencyList[value] = []
}
addEdge(vertex1: T, vertex2: T) {
this.adjacencyList[vertex1]?.push(vertex2)
this.adjacencyList[vertex2]?.push(vertex1)
}
}表示T不能赋值给类型符号...
发布于 2020-12-24 06:24:00
这是因为typescript不能保证T中的所有值实际上都是字符串、数字或符号(就typescript而言,唯一有效的对象键)。想象一下,如果您将number[]作为T提供给它,会发生什么。因此,添加一个它必须扩展string | number | symbol的子句
class Graph<T extends string | number | symbol> {
adjacencyList: {
[K in T]?: T[]
} = {}
addVertex(value: T) {
if (!this.adjacencyList[value]) this.adjacencyList[value] = []
}
addEdge(vertex1: T, vertex2: T) {
this.adjacencyList[vertex1]?.push(vertex2)
this.adjacencyList[vertex2]?.push(vertex1)
}
}然后,要向其提供枚举,请使用keyof typeof Enum获取由所有可能的字符串组成的联合类型:
const foo = new Graph<keyof typeof Cities>();https://stackoverflow.com/questions/65431527
复制相似问题