[英]Is it possible to use the name of a Typescript interface as a key in a generic type?
I would like to create a generic type that uses the name of the type parameter as a key in the resultant type.我想创建一个通用类型,它使用类型参数的名称作为结果类型中的键。 There is no need for such a type to exist in the transpiled JavaScript. It only needs to work for the purpose of type enforcement for the TypeScript source.
转译后的 JavaScript 中不需要存在这样的类型。它只需要为 TypeScript 源的类型强制执行目的而工作。
I first tried something like this...我第一次尝试这样的事情......
export type Wrapped<T> = {
`${T}`: T;
};
...and this... ...和这个...
export type Wrapped<T> = {
[nameof T]: T;
};
but these aren't valid.但这些都无效。
For example...例如...
interface MyInterface {
text: string;
}
const instance: MyInterface = { 'text': 'Hello!' };
const wrappedInstance: Wrapped<MyInterface> = { 'MyInterface': { 'text': 'World!' } };
Is TypeScript capable of creating such a type? TypeScript 能够创建这样的类型吗?
This is simply not possible on the current version of Typescript (4.6).这在 Typescript (4.6) 的当前版本上根本不可能。 The name of a type simply cannot be used as a type of any sort.
类型的名称根本不能用作任何类型的类型。
Whatever you are doing, you'll need to find another way.无论你在做什么,你都需要找到另一种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.