英文:
How to get the string representation of property names from a given typescript type
问题
以下是翻译好的部分:
我对TypeScript还很陌生,所以这个问题可能很简单。
假设我定义了一个类型如下:
type MyType = {
name: string,
age: number,
}
还有一个对象如下:
const o: MyType = {
name: "John Doe",
age: 42
}
我可以通过o["name"]
来访问name
属性。
是否可以使用类似于o[MyTypeProp.name]
的方式,而不是使用"name"这样的字符串,其中MyTypeProp.name
是从实际类型派生出来并包含每个属性名?
我曾经研究过MappedTypes,类似于以下的东西:
type MyTypeProp = {
[Property in keyof MyType]: Property;
};
但这并没有达到我希望的效果。
我的用例是为了更容易进行测试:我有一堆属性需要测试它们是否禁用,通过这种方式编写测试更加方便:
expect(allDisabled(model, ["isTrackingPresent", "isDistributionPresent", ...]))
比手动测试每个属性都要方便。
此外,去除那些"魔术字符串"会更加方便。
英文:
I am new to typescript so this question might be trivial.
Say I defined a type like
type MyType = {
name: string,
age: number,
}
and an object like
const o:MyType = {
name:"John Doe",
age:42
}
I could access the the name via o["name"]
.
Is it possible instead of using "name" something more safe like o[MyTypeProp.name]
where MyTypeProp.name
is derived from the actual type and contains every propertyname?
I was looking into MappedTypes and something similar to
type MyTypeProp = {
[Property in keyof MyType]: Property;
};
which gave me not what I was hoping for.
My usecase is to make testing easier: I have a bunch of properties to test whether they are disabled writing this
expect(allDisabled(model, ["isTrackingPresent", "isDistributionPresent", ...]))
is more comfortable than testing each and every manually.
On top getting rid of those "magic strings" would be more comfortable.
答案1
得分: 1
以下是翻译好的部分:
不能使用类型来生成一些运行时常量,因为在运行时所有类型都将消失。如果变量正确地类型化,那么就不需要这种对象。
可以生成一个类型,显示类型的结构:
const factory = {
name: {
type: "string",
},
data: {
type: "object",
fields: {
age: {
type: "number"
}
}
}
} as const
然后创建一个类型,用于将 "string"、"number" 转换为实际类型:
type TypeMap = {
string: string;
number: number;
}
并且使用一些映射类型,可以递归地遍历 factory
并生成一个类型。
英文:
It won't be possible to generate some runtime constants using types, since all types will be gone in runtime. If the variables are correctly typed then there is no need for this kind of object.
It would be possible to generate a type out of the object that would show the structure of the type:
const factory = {
name: {
type: "string",
},
data: {
type: "object",
fields: {
age: {
type: "number"
}
}
}
} as const
Then have a type for converting "string", "number" to actual type:
type TypeMap = {
string: string;
number: number;
}
And using some mapped type you could recursively go through the factory
and generate a type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论