我想创建一个接口来描述这样的结构...
const myObject: MyInterface = {
keys: ['a', 'b', 'c'], //Arbitrary length and string literals, array is readonly
props: {
a: null //OK
b: null //OK
c: null //OK
d: null //Invalid, 'd' is not in keys tuple
}
}从我收集的信息来看,TypeScript在编译时推断这一点应该不是问题,因为键数组不能更改,并且只有字符串字面量。下面是我目前尝试过的:
interface MyInterface {
readonly keys: readonly string[];
readonly props: Record<this['keys'][number],any>;
}这只能推断出键必须是字符串,而不是它们必须与给定的文字匹配。有没有办法实现我真正想要的东西?
发布于 2021-02-28 18:39:33
在这里使用type比使用interface更容易。
type Result<T extends ReadonlyArray<string>> = {
keys: T
} & {
[P in T[number]]: any // you can put here any type
};
type Test = Result<['a', 'b', 'c']>
const test: Test = {
keys: ['a', 'b', 'c'],
a: 1,
b: 2,
c: 3,
d: 3 // error
}发布于 2021-02-28 15:40:42
你需要定义你的常量类型。可能有更好的选择,但下面有两个建议。你可以将MyInterface或MyInterface2赋值给你的对象,在这两种情况下,任何与a,b或c不匹配的道具键都是不允许的。
const a = 'a';
const b = 'b';
const c = 'c';
type myConsts = {
a: any,
b: any,
c: any
}
type anyOfMyConsts = typeof a | typeof b | typeof c;
interface MyInterface {
readonly keys: readonly anyOfMyConsts[];
readonly props: Record<this['keys'][number],any>;
}
interface MyInterface2 {
readonly keys: readonly anyOfMyConsts[];
readonly props: myConsts;
}
const myObject: MyInterface2 = {
keys:['b', 'b', 'c'],
props: {
a:1,
b:2,
c:3
}
}https://stackoverflow.com/questions/66406531
复制相似问题