I have the following case in typescript:
type RecordKeys = 1 | 2 | 3
type RecordValues = "one" | "two" | "three"
function test(param: RecordKeys ): RecordValues {
switch(param) {
case(1): {
return 'one'
}
case(2): {
return 'two'
}
case(3): {
return "three"
}
}
}
Is there any way to correctly type this function to ensure that what is returned from this function corresponds to an actual map? For example : if param = 1 then "one" will be returned if param = 2 then "two" will be returned and so on.
CodePudding user response:
You can use a hashmap, here's an example:
const testMap: Record<number, string> = {
1: 'one',
2: 'two',
3: 'three'
}
// use the hashmap to get the value
function test2(param: number): String {
return testMap[param]
}
CodePudding user response:
For clarity, I'm posting an implementation of what @Vlaz suggested above with function overloads.
type RecordKeys = 1 | 2 | 3
function test(param: 1): "one"
function test(param: 2): "two"
function test(param: 3): "three"
function test(param: RecordKeys) {
switch(param){
case(1): {
return "one"
}
case(2): {
return "two"
}
case(3): {
return "three"
}
}
}
CodePudding user response:
you can make test
a generic function parameterized by key type and then rely on type inference:
type Rec = {
1: "one",
2: "two",
3: "three",
}
const rec: Rec = {
1: "one",
2: "two",
3: "three",
}
function test<K extends keyof Rec>(param: K): Rec[K] {
return rec[param]
}
const x = test(1) // typeof x === "one"
const y = test(2) // typeof y === "two"
const z = test(3) // typeof y === "three"
const fail = test(4) // Argument of type '4' is not assignable to parameter of type 'keyof Rec'
const fail2: 'two' = test(3) // Type '"three"' is not assignable to type "two"