How to use function overloading to implement a bidirectional mapping function?

Multi tool use
TL;DR
Try it online
I have two union types (both string literals) and a hard coded mapping object which maps these two types to each other.
type Digit = '1' | '2'
type Alpha = 'a' | 'b'
const map: Record<Digit, Alpha> & Record<Alpha, Digit> = {
'1': 'a',
'2': 'b',
'a': '1',
'b': '2'
}
The hard coded map works nice when being used agains singleton values.
let digit: Digit = '1'
let alpha = map[digit] // alpha is inferred as Alpha
let digit2 = map[alpha] // digit2 is inferred as Digit
Wrapping it with a function and then mapping over an array is also possible.
let digitArr: Digit = ['1', '2']
let alphaArr = digitArr.map(d => map[d]) // inferred as Alpha
But when I want to use only one function, with overloading, to achieve bidirectional mapping, i.e.
digitArr.map(mapping) // returns Alpha
alphaArr.map(mapping) // returns Digit
// where digitArr and alphaArr is deterministically typed as Digit and Alpha
the type system complains about it and I don't know how to make it happy.
My function definition:
function overloadedMapping(digit: Digit): Alpha
function overloadedMapping(alpha: Alpha): Digit
function overloadedMapping(key: Digit | Alpha): Digit | Alpha {
return map[key]
}
This function also works nice with singleton values and fails on one kind of array.
let d = overloadedMapping('a') // d is of type Digit
let a = overloadedMapping('1') // a is of type Alpha
let arr = alphaArr.map(overloadedMapping) // arr is of type Digit. works? why?
let arr2 = digitArr.map(overloadedMapping) // type inference fails!! why?
An interesting observation: When the overloading declaration order is switched, the array mapping which fails also alternates.
Try it online(same as the first link)
typescript typescript-typings function-overloading
add a comment |
TL;DR
Try it online
I have two union types (both string literals) and a hard coded mapping object which maps these two types to each other.
type Digit = '1' | '2'
type Alpha = 'a' | 'b'
const map: Record<Digit, Alpha> & Record<Alpha, Digit> = {
'1': 'a',
'2': 'b',
'a': '1',
'b': '2'
}
The hard coded map works nice when being used agains singleton values.
let digit: Digit = '1'
let alpha = map[digit] // alpha is inferred as Alpha
let digit2 = map[alpha] // digit2 is inferred as Digit
Wrapping it with a function and then mapping over an array is also possible.
let digitArr: Digit = ['1', '2']
let alphaArr = digitArr.map(d => map[d]) // inferred as Alpha
But when I want to use only one function, with overloading, to achieve bidirectional mapping, i.e.
digitArr.map(mapping) // returns Alpha
alphaArr.map(mapping) // returns Digit
// where digitArr and alphaArr is deterministically typed as Digit and Alpha
the type system complains about it and I don't know how to make it happy.
My function definition:
function overloadedMapping(digit: Digit): Alpha
function overloadedMapping(alpha: Alpha): Digit
function overloadedMapping(key: Digit | Alpha): Digit | Alpha {
return map[key]
}
This function also works nice with singleton values and fails on one kind of array.
let d = overloadedMapping('a') // d is of type Digit
let a = overloadedMapping('1') // a is of type Alpha
let arr = alphaArr.map(overloadedMapping) // arr is of type Digit. works? why?
let arr2 = digitArr.map(overloadedMapping) // type inference fails!! why?
An interesting observation: When the overloading declaration order is switched, the array mapping which fails also alternates.
Try it online(same as the first link)
typescript typescript-typings function-overloading
1
Just a side note: enums are bidirectional maps already built into TypeScript. You can create one (enum MyMap { Alpha = 0, Beta = 1}
) and access both keys and values (MyMap['Alpha']
,MyMap[0]
).
– Karol Majewski
Dec 28 '18 at 3:50
Hi Karol, thanks. Whileenum
does provide a bidirectional mapping, it doesn't match my needs. Both side of the mapping needs to be arbitrary string literals and a string based enum is not bidirectional mapped. And still, mapping over an array with one function is not possible.
– Nandiin Bao
Dec 28 '18 at 5:56
add a comment |
TL;DR
Try it online
I have two union types (both string literals) and a hard coded mapping object which maps these two types to each other.
type Digit = '1' | '2'
type Alpha = 'a' | 'b'
const map: Record<Digit, Alpha> & Record<Alpha, Digit> = {
'1': 'a',
'2': 'b',
'a': '1',
'b': '2'
}
The hard coded map works nice when being used agains singleton values.
let digit: Digit = '1'
let alpha = map[digit] // alpha is inferred as Alpha
let digit2 = map[alpha] // digit2 is inferred as Digit
Wrapping it with a function and then mapping over an array is also possible.
let digitArr: Digit = ['1', '2']
let alphaArr = digitArr.map(d => map[d]) // inferred as Alpha
But when I want to use only one function, with overloading, to achieve bidirectional mapping, i.e.
digitArr.map(mapping) // returns Alpha
alphaArr.map(mapping) // returns Digit
// where digitArr and alphaArr is deterministically typed as Digit and Alpha
the type system complains about it and I don't know how to make it happy.
My function definition:
function overloadedMapping(digit: Digit): Alpha
function overloadedMapping(alpha: Alpha): Digit
function overloadedMapping(key: Digit | Alpha): Digit | Alpha {
return map[key]
}
This function also works nice with singleton values and fails on one kind of array.
let d = overloadedMapping('a') // d is of type Digit
let a = overloadedMapping('1') // a is of type Alpha
let arr = alphaArr.map(overloadedMapping) // arr is of type Digit. works? why?
let arr2 = digitArr.map(overloadedMapping) // type inference fails!! why?
An interesting observation: When the overloading declaration order is switched, the array mapping which fails also alternates.
Try it online(same as the first link)
typescript typescript-typings function-overloading
TL;DR
Try it online
I have two union types (both string literals) and a hard coded mapping object which maps these two types to each other.
type Digit = '1' | '2'
type Alpha = 'a' | 'b'
const map: Record<Digit, Alpha> & Record<Alpha, Digit> = {
'1': 'a',
'2': 'b',
'a': '1',
'b': '2'
}
The hard coded map works nice when being used agains singleton values.
let digit: Digit = '1'
let alpha = map[digit] // alpha is inferred as Alpha
let digit2 = map[alpha] // digit2 is inferred as Digit
Wrapping it with a function and then mapping over an array is also possible.
let digitArr: Digit = ['1', '2']
let alphaArr = digitArr.map(d => map[d]) // inferred as Alpha
But when I want to use only one function, with overloading, to achieve bidirectional mapping, i.e.
digitArr.map(mapping) // returns Alpha
alphaArr.map(mapping) // returns Digit
// where digitArr and alphaArr is deterministically typed as Digit and Alpha
the type system complains about it and I don't know how to make it happy.
My function definition:
function overloadedMapping(digit: Digit): Alpha
function overloadedMapping(alpha: Alpha): Digit
function overloadedMapping(key: Digit | Alpha): Digit | Alpha {
return map[key]
}
This function also works nice with singleton values and fails on one kind of array.
let d = overloadedMapping('a') // d is of type Digit
let a = overloadedMapping('1') // a is of type Alpha
let arr = alphaArr.map(overloadedMapping) // arr is of type Digit. works? why?
let arr2 = digitArr.map(overloadedMapping) // type inference fails!! why?
An interesting observation: When the overloading declaration order is switched, the array mapping which fails also alternates.
Try it online(same as the first link)
typescript typescript-typings function-overloading
typescript typescript-typings function-overloading
asked Dec 28 '18 at 3:35
Nandiin Bao
927520
927520
1
Just a side note: enums are bidirectional maps already built into TypeScript. You can create one (enum MyMap { Alpha = 0, Beta = 1}
) and access both keys and values (MyMap['Alpha']
,MyMap[0]
).
– Karol Majewski
Dec 28 '18 at 3:50
Hi Karol, thanks. Whileenum
does provide a bidirectional mapping, it doesn't match my needs. Both side of the mapping needs to be arbitrary string literals and a string based enum is not bidirectional mapped. And still, mapping over an array with one function is not possible.
– Nandiin Bao
Dec 28 '18 at 5:56
add a comment |
1
Just a side note: enums are bidirectional maps already built into TypeScript. You can create one (enum MyMap { Alpha = 0, Beta = 1}
) and access both keys and values (MyMap['Alpha']
,MyMap[0]
).
– Karol Majewski
Dec 28 '18 at 3:50
Hi Karol, thanks. Whileenum
does provide a bidirectional mapping, it doesn't match my needs. Both side of the mapping needs to be arbitrary string literals and a string based enum is not bidirectional mapped. And still, mapping over an array with one function is not possible.
– Nandiin Bao
Dec 28 '18 at 5:56
1
1
Just a side note: enums are bidirectional maps already built into TypeScript. You can create one (
enum MyMap { Alpha = 0, Beta = 1}
) and access both keys and values (MyMap['Alpha']
, MyMap[0]
).– Karol Majewski
Dec 28 '18 at 3:50
Just a side note: enums are bidirectional maps already built into TypeScript. You can create one (
enum MyMap { Alpha = 0, Beta = 1}
) and access both keys and values (MyMap['Alpha']
, MyMap[0]
).– Karol Majewski
Dec 28 '18 at 3:50
Hi Karol, thanks. While
enum
does provide a bidirectional mapping, it doesn't match my needs. Both side of the mapping needs to be arbitrary string literals and a string based enum is not bidirectional mapped. And still, mapping over an array with one function is not possible.– Nandiin Bao
Dec 28 '18 at 5:56
Hi Karol, thanks. While
enum
does provide a bidirectional mapping, it doesn't match my needs. Both side of the mapping needs to be arbitrary string literals and a string based enum is not bidirectional mapped. And still, mapping over an array with one function is not possible.– Nandiin Bao
Dec 28 '18 at 5:56
add a comment |
1 Answer
1
active
oldest
votes
When overload resolution fails to match your callback with the desired signature, you can tell TypeScript what your intention is by providing the type parameter explicitly:
let arr2 = digitArr.map<Alpha>(overloadedMapping)
Now your transformation will be treated as (value: Digit, index: number, array: Digit) => Alpha
.
In this case, opting out of the point-free style will help TypeScript match the overload as well:
let arr2 = digitArr.map(digit => overloadedMapping(digit))
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53953394%2fhow-to-use-function-overloading-to-implement-a-bidirectional-mapping-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
When overload resolution fails to match your callback with the desired signature, you can tell TypeScript what your intention is by providing the type parameter explicitly:
let arr2 = digitArr.map<Alpha>(overloadedMapping)
Now your transformation will be treated as (value: Digit, index: number, array: Digit) => Alpha
.
In this case, opting out of the point-free style will help TypeScript match the overload as well:
let arr2 = digitArr.map(digit => overloadedMapping(digit))
add a comment |
When overload resolution fails to match your callback with the desired signature, you can tell TypeScript what your intention is by providing the type parameter explicitly:
let arr2 = digitArr.map<Alpha>(overloadedMapping)
Now your transformation will be treated as (value: Digit, index: number, array: Digit) => Alpha
.
In this case, opting out of the point-free style will help TypeScript match the overload as well:
let arr2 = digitArr.map(digit => overloadedMapping(digit))
add a comment |
When overload resolution fails to match your callback with the desired signature, you can tell TypeScript what your intention is by providing the type parameter explicitly:
let arr2 = digitArr.map<Alpha>(overloadedMapping)
Now your transformation will be treated as (value: Digit, index: number, array: Digit) => Alpha
.
In this case, opting out of the point-free style will help TypeScript match the overload as well:
let arr2 = digitArr.map(digit => overloadedMapping(digit))
When overload resolution fails to match your callback with the desired signature, you can tell TypeScript what your intention is by providing the type parameter explicitly:
let arr2 = digitArr.map<Alpha>(overloadedMapping)
Now your transformation will be treated as (value: Digit, index: number, array: Digit) => Alpha
.
In this case, opting out of the point-free style will help TypeScript match the overload as well:
let arr2 = digitArr.map(digit => overloadedMapping(digit))
answered Dec 28 '18 at 14:34


Karol Majewski
1,22617
1,22617
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53953394%2fhow-to-use-function-overloading-to-implement-a-bidirectional-mapping-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
6 nRIO5LVvDUGA,1D tlTgC,wiS6WfbyPQJ5bEhMVb7WLlqMF4vmM0cH4douGZXgcNTAN
1
Just a side note: enums are bidirectional maps already built into TypeScript. You can create one (
enum MyMap { Alpha = 0, Beta = 1}
) and access both keys and values (MyMap['Alpha']
,MyMap[0]
).– Karol Majewski
Dec 28 '18 at 3:50
Hi Karol, thanks. While
enum
does provide a bidirectional mapping, it doesn't match my needs. Both side of the mapping needs to be arbitrary string literals and a string based enum is not bidirectional mapped. And still, mapping over an array with one function is not possible.– Nandiin Bao
Dec 28 '18 at 5:56