I wanna narrow down type when returning data from function smartly (hopefully without using if statement etc)
I have the following code
enum TypeData {
Data1 = 'data1',
Data2 = 'data2',
Data3 = 'data3',
}
type DataType = {
[TypeData.Data1]: {d1: number};
[TypeData.Data2]: {d2: string};
[TypeData.Data3]: {d3: number};
}
type Child = DataType[TypeData]
const dataType: DataType = {
[TypeData.Data1]: {d1: 1},
[TypeData.Data2]: {d2: 2},
[TypeData.Data3]: {d3: 3},
}
const getChild = (typeData: TypeData): Child => {
return dataType[typeData]
}
const data = getChild(TypeData.Data2)
In the code, the function returns Child
type, but Child
type represents like
type Child = {
d3: number;
} | {
d1: string;
} | {
d2: number;
}
instead of specific data type like { d3: number }
. How to make it possible to specify the return data type instead of union of all types?
You have to make use of TypeScript Generics in order to return the correct type depending on the given input. Like so:
enum TypeData {
Data1 = 'data1',
Data2 = 'data2',
Data3 = 'data3',
}
type DataType = {
[TypeData.Data1]: {d1: number};
[TypeData.Data2]: {d2: number};
[TypeData.Data3]: {d3: number};
}
const dataType: DataType = {
[TypeData.Data1]: {d1: 1},
[TypeData.Data2]: {d2: 2},
[TypeData.Data3]: {d3: 3},
}
const getChild = <T extends TypeData>(typeData: T): DataType[T] => {
return dataType[typeData]
}
const data = getChild(TypeData.Data2)
See here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.