[英]Result as object where key is each value in an array
I am trying to figure out how it is possible to define the result of primaryKey
where it is an object and each key is a value from the array $primaryKey
. 我试图弄清楚怎么可能在一个对象是
primaryKey
情况下定义结果,并且每个键都是数组$primaryKey
一个值。 However I am not sure how this can be done. 但是,我不确定如何做到这一点。 I don't think I can use
keyof this.$primaryKey
as I tried and get an error. 我认为我无法在尝试使用
keyof this.$primaryKey
并得到错误时使用它。 How (if possible) can this be done? 如何(如果可能)做到这一点?
TypeScript Playground TypeScript游乐场
export type PrimaryKey = { [key: keyof Model.$primaryKey]: DBCell }
export abstract class Model extends DB {
public $primaryKey: string[] = ['a', 'b']
public get primaryKey(): PrimaryKey {
return { a: 123, b: 456 }
}
}
I've managed to get PrimaryKey
defined with the following changes: 我设法通过以下更改定义了
PrimaryKey
:
public $primaryKey = ['a', 'b'] as const;
as const
causes the type of $primaryKey
to be inferred as ['a', 'b']
(a tuple of literal string types) instead of a plain string[]
. as const
导致将$primaryKey
的类型推断为['a', 'b']
(文字字符串类型的元组),而不是纯string[]
。
You can then turn this into 'a' | 'b'
然后,您可以将其转换为
'a' | 'b'
'a' | 'b'
using index types: 使用索引类型的
'a' | 'b'
:
Model["$primaryKey"][number]
First set of brackets extracts the tuple type, the second set turns it into a union of its values. 第一组括号提取出元组类型,第二组括号将其变成其值的并集。
From there it's trivial to create an object using the Record
utility type: 从那里开始,使用
Record
实用程序类型创建对象很简单:
export type PrimaryKey = Record<Model["$primaryKey"][number], DBCell>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.