[英]Typescript generic associative array
I would like to get deep value from the object, for example result when generic is "books":我想从 object 中获得深刻的价值,例如当泛型为“书籍”时的结果:
fieldName: {author: "", langauge: "", translation: ""}
export const COLLECTIONS_MOCKUP = {
books: {
author: "",
language: "",
translation: "",
},
vehicle: {
model: "",
type: "",
color: "",
},
}
export interface IOptionalField<T> {
fieldName: typeof COLLECTIONS_MOCKUP[T]; // how to make it work, it throws an error
valueType: string | number | boolean | Date;
isAdded?: boolean;
}
You need a generic constraint, so that T
must be a key of COLLECTIONS_MOCKUP
.您需要一个通用约束,因此
T
必须是COLLECTIONS_MOCKUP
的键。
export interface IOptionalField<T extends keyof typeof COLLECTIONS_MOCKUP> {
fieldName: typeof COLLECTIONS_MOCKUP[T];
valueType: string | number | boolean | Date;
isAdded?: boolean;
}
This works as you expected:这可以按您的预期工作:
const books: IOptionalField<"books"> = {
fieldName: {
author: "",
language: "",
translation: ""
},
valueType: 0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.