基于路径字符串的类型

时间:2019-04-16 19:22:52

标签: typescript

我正在构建一个控件,用户可以在其中传递路径字符串,以表示如何访问与其绑定的对象上的某些数据。

有什么方法可以定义类型,以便根据其他属性的值来键入其属性?

一个例子应该阐明我的意思。与此类似:

type RowPath: string;
type ColumnPath: string;
type FieldNamePath: string;

interface Item {
    [key: RowPath]: number;
    [key: ColumnPath]: number;
    [key: FieldNamePath]: string;
}

class MyControl {

    constructor(
        private rowPath: RowPath, 
        private columnPath: ColumnPath, 
        private fieldNamePath: FieldNamePath,
        private items: Item[]) { }
}

我想这样做是因为我可以使用类型安全的方式访问items而不是使用any

const item = this.items[0];
const rowNum = item[this.rowPath]; //TypeScript knows this is a number
const colNum = item[this.columnPath]; //TypeScript knows this is a number
const fieldName = item[this.fieldNamePath]; //TypeScript knows this is a string

这似乎对我有用,除了TypeScript禁止其中包含类型别名的索引器。有什么办法吗?

0 个答案:

没有答案
相关问题