I'm trying to create a large object whose values are limited to only 3 types: Texture, Geometry, ScriptMy 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 assignthis.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 这篇关于打字稿:限制对象值的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-13 05:38