打字稿:限制对象值的类型 [英] Typescript: limiting types in object values
问题描述
我正在尝试创建一个大对象,其值仅限于 3 种类型:Texture
、Geometry
、Script
我的对象看起来像这样:
var 资产:资产 = {天空:<纹理>,地面:<纹理>,城市:<几何>,人们:<脚本>,汽车:<脚本>,太阳:<圆圈>//<--这应该失败,因为它不是 3 种类型之一//...}
如何声明 Assets
接口,使每个键值对中的值仅限于这 3 种类型?我尝试从以下开始:
界面资产{关键:质地 |几何 |脚本;}
但是当我分配时它会中断
this.assets = {sky: new Texture()}
因为它只需要 key
而不是 sky
.有没有办法在对象中不嵌套对象的情况下实现这一点?
怎么样:
type Assets = {[key: string]: 纹理 |几何 |脚本;}
该类型将允许您请求的类型之一的字符串键和值.
有关该主题的更多信息:可索引类型>
I'm trying to create a large object whose values are limited to only 3 types: Texture
, Geometry
, Script
My object would look something like this:
var assets: Assets = {
sky: <Texture>,
ground: <Texture>,
city: <Geometry>,
people: <Script>,
cars: <Script>,
sun: <Circle> // <--This should fail because it's not one of the 3 types
//...
}
How can I declare the Assets
interface so the value in each key-value pair is limited to these 3 types? I tried starting with:
interface Assets{
key: Texture | Geometry | Script;
}
but then it breaks when I assign
this.assets = {sky: new Texture()}
Because it's expecting only key
instead of sky
. Is there any way of achieving this without nesting objects within objects?
How about:
type Assets = {
[key: string]: Texture | Geometry | Script;
}
That type will allow for string keys and values of one of the types you requested.
More on the subject: Indexable Types
这篇关于打字稿:限制对象值的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!