我尝试通过计算属性访问对象元素。我知道一个事实,这个计算出的字符串将具有某种形式,对应于某些类型的元素。但是TypeScript会推断任何as类型,因为“边界没有索引签名”。
到目前为止,唯一有效的方法是将访问器字符串转换为它可以采用的所有可能值的并集,但是TypeScript是否应该能够自动干预呢?
下面的示例代码:
type Direction =
| 'top'
| 'bottom'
| 'left'
| 'right'
| 'topLeft'
| 'topRight'
| 'bottomLeft'
| 'bottomRight';
interface Boundary {
top: number;
topAlternatives: number[];
bottom: number;
bottomAlternatives: number[];
left: number;
leftAlternatives: number[];
right: number;
rightAlternatives: number[];
topLeft: number;
topLeftAlternatives: number[];
topRight: number;
topRightAlternatives: number[];
bottomLeft: number;
bottomLeftAlternatives: number[];
bottomRight: number;
bottomRightAlternatives: number[];
}
const direction: Direction = 'top';
const accessorString = `${direction}Alternatives`;
const object: Boundary = {...};
const element = object[accessorString]; // type is clearly number[], but it is not infered
我们非常感谢您的帮助!
答案 0 :(得分:2)
在执行字符串操作时,Typescript无法推断字符串文字类型。因此,即使对我们来说accessorString
很明显'topAlternatives'
打字稿也不知道这一点。
您可以强制转换为keyof Boundary
,但结果将是number | number[]
const direction: Direction = 'top';
const accessorString = `${direction}Alternatives` as keyof Boundary;
const object: Boundary = { } as Boundary;
const element = object[accessorString]; // number[] | number
或者您可以过滤number[]
属性并将其强制转换为:
type KeysOfType<T, TValue> = {
[P in keyof T]-?: T[P] extends TValue ? P : never
}[keyof T]
const direction: Direction = 'top';
const accessorString = `${direction}Alternatives` as KeysOfType<Boundary, number[]>;
const object: Boundary = { } as Boundary;
const element = object[accessorString]; // number[]
答案 1 :(得分:0)
const对象:{[边界键中的K]:K延伸方向? number:number []} = {...};
然后object [accessorString]将相应地返回类型