Typescript是否能够强制值的域在同一对象中声明的一组键名内?



我对Typescript很陌生,我真的很欣赏它的类型检查功能。

我需要了解它的功能是否有可能在编译时检查一个值的域是否在同一对象中声明的一组键名内?

下面的例子将有助于澄清我的问题。我有这些对象和类型定义:
type ElemField = { name: string }
type Elem = Record<string, ElemField>
type Relation = { path: string[] }
type MySchema = {
elem: Record<string, Elem>,
relations: Record<string, Relation>
}
const test: MySchema = {
elem: {
elem1: {
prop1: { name: 'string' },
},
elem2: {
prop2: { name: 'string' },
prop3: { name: 'string' },
},
elem3: {
prop4: { name: 'string' },
}
},
relations: {
relation1: {
path: ['elem2', 'elem1'],
},
relation2: {
path: ['elem3', 'elem1'],
}
}
}

我想知道是否有可能在编译时检查path数组是否仅在根级elements键的键域内包含值。

我不明白如果使用keyof,泛型,或其他一些Typescript特性,它是可能定义这样的关系。

编辑:感谢Shahriar Shojib我得到了第一个有效的解决方案。但我想知道是否有可能在不使用函数的情况下实现这一点,而只是为对象指定类型。

我相信有更好的方法来实现这一点,但这应该适用于您的用例。

type ElemField = { name: string }
type Elem = Record<string, ElemField>
type Relation <T> = { path: T[] }
type MySchema<T extends Record<string, Elem>>  = {
elem: T,
relations: Record<string, Relation<keyof T>>
}

function createSchema<T extends Record<string, Elem>>(schema:MySchema<T>) {
return schema;
}
createSchema({
elem: {
elem1: {
prop1: { name: 'string' },
},
elem2: {
prop2: { name: 'string' },
prop3: { name: 'string' },
},
elem3: {
prop4: { name: 'string' },
}
},
relations: {
relation1: {
path: ['elem2', 'elem1', 'elem5'], // error since it does not exist
},
relation2: {
path: ['elem3', 'elem1'],
}
}
})

最新更新