Typescript 类型化类映射结构
我是Typescript新手,我基本上是在尝试创建一个类型化映射结构,其中的值应该绑定到键。这在一些没有类型的psuedo JS代码中得到了最好的解释:Typescript 类型化类映射结构,typescript,Typescript,我是Typescript新手,我基本上是在尝试创建一个类型化映射结构,其中的值应该绑定到键。这在一些没有类型的psuedo JS代码中得到了最好的解释: const propertyA = "PropertyA"; const propertyB = "PropertyB"; const item1 = "item1"; const item2 = "item2"; const item3 = "item3"; const item4 = "item4"; const arrayA = [i
const propertyA = "PropertyA";
const propertyB = "PropertyB";
const item1 = "item1";
const item2 = "item2";
const item3 = "item3";
const item4 = "item4";
const arrayA = [item1, item2]; // Should only be used by propertyA
const arrayB = [item1, item3, item4]; // Should only be used by propertyB
{
PropertyA: arrayA,
PropertyB: arrayB,
...
}
这有点做作,但简而言之,我希望能够阻止PropertyB
被分配arrayB
,因此这不可能:
{
PropertyA: arrayB,
PropertyB: arrayA,
...
}
作为Typescript的新手,我环顾四周,发现了一些记录的示例,并认为它也可以为我创建一个联合
,如下所示:
// Typings
type PropertyA = "PropertyA";
type PropertyB = "PropertyB";
type PropertyC = "PropertyC";
type PropertyTypes = PropertyA | PropertyB | PropertyC;
type PropertyAItems = "A" | "B" | "C";
type PropertyBItems = "C" | "D";
type PropertyCItems = "C" | "F";
type PropertyMap =
| Record<PropertyA, Array<PropertyAItems>>
| Record<PropertyB, Array<PropertyBItems>>
| Record<PropertyC, Array<PropertyCItems>>;
// The implementation
const testMap: PropertyMap = {
PropertyA: ["A", "B", "C"],
PropertyB: ["C", "D"],
PropertyC: ["C", "F"]
};
所以。。。很明显,我在某个地方做错了什么,所以我非常感谢你的帮助,但更重要的是,这是正确的方法吗?我想听听其他的建议。正如我所说,我对Typescript还不熟悉,所以这是一个全新的世界。描述该接口的更简单方法是
interface PropertyMap {
PropertyA: Array<"A" | "B" | "C">
PropertyB: Array<"C" | "D">
PropertyC: Array<"C" | "F">
}
如果您确实希望值是数组而不是元组。描述该接口的更简单方法是
interface PropertyMap {
PropertyA: Array<"A" | "B" | "C">
PropertyB: Array<"C" | "D">
PropertyC: Array<"C" | "F">
}
假设您确实希望值是数组而不是元组。那么,您是在寻找元组吗?例如,像PropertyA:[string,string]
这样的签名将阻止[“A”,“b”,“c”]
被分配到那里。嗯,在这种情况下,如果我理解正确,消费者将能够为PropertyB和PropertyC使用错误的数组,因为两者都是[string,string]
。我希望每个属性的可用值都是有限的,即,PropertyB
只能为其分配一个PropertyBItems
数组。这只是意味着您希望PropertyB:PropertyBItems[]
或PropertyBItem:[PropertyBItem,PropertyBItem]
取决于您想要的是数字还是元组。您的属性映射可能应该使用(&
)而不是(|
),但是Record&Record
是一种迂回的说法,{a:string,b:number}
,所以@georg的方向是正确的。“将值绑定到键的类型化映射”就是它的用途!那么,你在找元组吗?例如,像PropertyA:[string,string]
这样的签名将阻止[“A”,“b”,“c”]
被分配到那里。嗯,在这种情况下,如果我理解正确,消费者将能够为PropertyB和PropertyC使用错误的数组,因为两者都是[string,string]
。我希望每个属性的可用值都是有限的,即,PropertyB
只能为其分配一个PropertyBItems
数组。这只是意味着您希望PropertyB:PropertyBItems[]
或PropertyBItem:[PropertyBItem,PropertyBItem]
取决于您想要的是数字还是元组。您的属性映射可能应该使用(&
)而不是(|
),但是Record&Record
是一种迂回的说法,{a:string,b:number}
,所以@georg的方向是正确的。“将值绑定到键的类型化映射”就是它的用途!这就是我最终采取的方法。谢谢大家的帮助和建议!这就是我最终采取的方法。谢谢大家的帮助和建议!
const testMap: PropertyMap = {
PropertyA: ["A", "B", "B", "B"],
PropertyB: ["C", "D", "D", "D", "D"],
PropertyC: ["C", "F", "C", "F"]
};