ts中如何动态的定义变量的类型?

比如当type为1的时候 data的数据类型为number 当type为2的时候 data的数据类型为string

阅读 2.6k
2 个回答

type DataType = {
1: number;
2: string;
}
const type = 2
const type2 = 1
const data1 : DataType[typeof type] = '1'
const data2 : DataType[typeof type2] = 1

这样?

type A = { type: 1, data: string; } | { type: 2, data: number; }
const fn = (v: A) => {
    if (v.type === 1) {
        // v.data 
    }
}