Extract string union from array of objects
I have following object
[{
"key": "a1",
...
}, {
"key": "a2",
...
}, ...]
Is it possible to extract union type "a1" | "a2" | ... from this object?
I am aware that it is possible to extract it from ['a1', 'a2', ...] by using tuple API, which was presented here TypeScript String Union to String Array, but I can't figure it out for object array
typescript typescript-typings
add a comment |
I have following object
[{
"key": "a1",
...
}, {
"key": "a2",
...
}, ...]
Is it possible to extract union type "a1" | "a2" | ... from this object?
I am aware that it is possible to extract it from ['a1', 'a2', ...] by using tuple API, which was presented here TypeScript String Union to String Array, but I can't figure it out for object array
typescript typescript-typings
add a comment |
I have following object
[{
"key": "a1",
...
}, {
"key": "a2",
...
}, ...]
Is it possible to extract union type "a1" | "a2" | ... from this object?
I am aware that it is possible to extract it from ['a1', 'a2', ...] by using tuple API, which was presented here TypeScript String Union to String Array, but I can't figure it out for object array
typescript typescript-typings
I have following object
[{
"key": "a1",
...
}, {
"key": "a2",
...
}, ...]
Is it possible to extract union type "a1" | "a2" | ... from this object?
I am aware that it is possible to extract it from ['a1', 'a2', ...] by using tuple API, which was presented here TypeScript String Union to String Array, but I can't figure it out for object array
typescript typescript-typings
typescript typescript-typings
asked Jan 2 at 16:23
Natalia Natalia
162
162
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Basically you just want to do a lookup of the "key" property of the elements of the array, where the elements of an array can be found by looking up its number property. Unfortunately, the hard part is getting that to show up as anything but "string".
const val = [{ key: "a1" }, { key: "a2" }]; // Array<{key: string}>
type ValueAtKey = (typeof val)[number]["key"]; // string 🙁
That's because the compiler infers val to just be an array of objects with a string value. The compiler uses some heuristics to determine when to widen literals, and in the above case, the exact string literals have been widened to string.
One of the ways to hint to the compiler that a value like "a1" should stay narrowed to "a1" instead of widened to string is to have the value match a type constrained to string (or a union containing it). The following is a helper function I sometimes use to do this:
type Narrowable =
string | number | boolean | symbol | object |
null | undefined | void | ((...args: any) => any) | {};
const literally = <T extends { [k: string]: V | T } | Array<{ [k: string]: V | T }>,
V extends Narrowable>(t: T) => t;
The literally() function just returns its argument, but the type tends to be narrower. Yes, it's ugly.
Now you can do:
const val = literally([{ key: "a1" }, { key: "a2" }]); // Array<{key: "a1"}|{key: "a2"}>
type ValueAtKey = (typeof val)[number]["key"]; // "a1" | "a2" 🙂
The val object is the same at runtime, but the TypeScript compiler now sees it as an array of values of type {key: "a1"} or {key: "a2"}. Then the lookup done for ValueAtKey gives you the union type you're looking for.
(Note that I assume you don't care about the ordering of val here. That is, you are fine treating it as an array instead of as a tuple. Since the union type "a1" | "a2" doesn't have an inherent ordering, then the array should be sufficient.)
Hope that helps; good luck!
Thatliterallyhelper is a good tip - thanks!
– Jesse Hallett
Jan 2 at 17:09
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%2f54009764%2fextract-string-union-from-array-of-objects%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
Basically you just want to do a lookup of the "key" property of the elements of the array, where the elements of an array can be found by looking up its number property. Unfortunately, the hard part is getting that to show up as anything but "string".
const val = [{ key: "a1" }, { key: "a2" }]; // Array<{key: string}>
type ValueAtKey = (typeof val)[number]["key"]; // string 🙁
That's because the compiler infers val to just be an array of objects with a string value. The compiler uses some heuristics to determine when to widen literals, and in the above case, the exact string literals have been widened to string.
One of the ways to hint to the compiler that a value like "a1" should stay narrowed to "a1" instead of widened to string is to have the value match a type constrained to string (or a union containing it). The following is a helper function I sometimes use to do this:
type Narrowable =
string | number | boolean | symbol | object |
null | undefined | void | ((...args: any) => any) | {};
const literally = <T extends { [k: string]: V | T } | Array<{ [k: string]: V | T }>,
V extends Narrowable>(t: T) => t;
The literally() function just returns its argument, but the type tends to be narrower. Yes, it's ugly.
Now you can do:
const val = literally([{ key: "a1" }, { key: "a2" }]); // Array<{key: "a1"}|{key: "a2"}>
type ValueAtKey = (typeof val)[number]["key"]; // "a1" | "a2" 🙂
The val object is the same at runtime, but the TypeScript compiler now sees it as an array of values of type {key: "a1"} or {key: "a2"}. Then the lookup done for ValueAtKey gives you the union type you're looking for.
(Note that I assume you don't care about the ordering of val here. That is, you are fine treating it as an array instead of as a tuple. Since the union type "a1" | "a2" doesn't have an inherent ordering, then the array should be sufficient.)
Hope that helps; good luck!
Thatliterallyhelper is a good tip - thanks!
– Jesse Hallett
Jan 2 at 17:09
add a comment |
Basically you just want to do a lookup of the "key" property of the elements of the array, where the elements of an array can be found by looking up its number property. Unfortunately, the hard part is getting that to show up as anything but "string".
const val = [{ key: "a1" }, { key: "a2" }]; // Array<{key: string}>
type ValueAtKey = (typeof val)[number]["key"]; // string 🙁
That's because the compiler infers val to just be an array of objects with a string value. The compiler uses some heuristics to determine when to widen literals, and in the above case, the exact string literals have been widened to string.
One of the ways to hint to the compiler that a value like "a1" should stay narrowed to "a1" instead of widened to string is to have the value match a type constrained to string (or a union containing it). The following is a helper function I sometimes use to do this:
type Narrowable =
string | number | boolean | symbol | object |
null | undefined | void | ((...args: any) => any) | {};
const literally = <T extends { [k: string]: V | T } | Array<{ [k: string]: V | T }>,
V extends Narrowable>(t: T) => t;
The literally() function just returns its argument, but the type tends to be narrower. Yes, it's ugly.
Now you can do:
const val = literally([{ key: "a1" }, { key: "a2" }]); // Array<{key: "a1"}|{key: "a2"}>
type ValueAtKey = (typeof val)[number]["key"]; // "a1" | "a2" 🙂
The val object is the same at runtime, but the TypeScript compiler now sees it as an array of values of type {key: "a1"} or {key: "a2"}. Then the lookup done for ValueAtKey gives you the union type you're looking for.
(Note that I assume you don't care about the ordering of val here. That is, you are fine treating it as an array instead of as a tuple. Since the union type "a1" | "a2" doesn't have an inherent ordering, then the array should be sufficient.)
Hope that helps; good luck!
Thatliterallyhelper is a good tip - thanks!
– Jesse Hallett
Jan 2 at 17:09
add a comment |
Basically you just want to do a lookup of the "key" property of the elements of the array, where the elements of an array can be found by looking up its number property. Unfortunately, the hard part is getting that to show up as anything but "string".
const val = [{ key: "a1" }, { key: "a2" }]; // Array<{key: string}>
type ValueAtKey = (typeof val)[number]["key"]; // string 🙁
That's because the compiler infers val to just be an array of objects with a string value. The compiler uses some heuristics to determine when to widen literals, and in the above case, the exact string literals have been widened to string.
One of the ways to hint to the compiler that a value like "a1" should stay narrowed to "a1" instead of widened to string is to have the value match a type constrained to string (or a union containing it). The following is a helper function I sometimes use to do this:
type Narrowable =
string | number | boolean | symbol | object |
null | undefined | void | ((...args: any) => any) | {};
const literally = <T extends { [k: string]: V | T } | Array<{ [k: string]: V | T }>,
V extends Narrowable>(t: T) => t;
The literally() function just returns its argument, but the type tends to be narrower. Yes, it's ugly.
Now you can do:
const val = literally([{ key: "a1" }, { key: "a2" }]); // Array<{key: "a1"}|{key: "a2"}>
type ValueAtKey = (typeof val)[number]["key"]; // "a1" | "a2" 🙂
The val object is the same at runtime, but the TypeScript compiler now sees it as an array of values of type {key: "a1"} or {key: "a2"}. Then the lookup done for ValueAtKey gives you the union type you're looking for.
(Note that I assume you don't care about the ordering of val here. That is, you are fine treating it as an array instead of as a tuple. Since the union type "a1" | "a2" doesn't have an inherent ordering, then the array should be sufficient.)
Hope that helps; good luck!
Basically you just want to do a lookup of the "key" property of the elements of the array, where the elements of an array can be found by looking up its number property. Unfortunately, the hard part is getting that to show up as anything but "string".
const val = [{ key: "a1" }, { key: "a2" }]; // Array<{key: string}>
type ValueAtKey = (typeof val)[number]["key"]; // string 🙁
That's because the compiler infers val to just be an array of objects with a string value. The compiler uses some heuristics to determine when to widen literals, and in the above case, the exact string literals have been widened to string.
One of the ways to hint to the compiler that a value like "a1" should stay narrowed to "a1" instead of widened to string is to have the value match a type constrained to string (or a union containing it). The following is a helper function I sometimes use to do this:
type Narrowable =
string | number | boolean | symbol | object |
null | undefined | void | ((...args: any) => any) | {};
const literally = <T extends { [k: string]: V | T } | Array<{ [k: string]: V | T }>,
V extends Narrowable>(t: T) => t;
The literally() function just returns its argument, but the type tends to be narrower. Yes, it's ugly.
Now you can do:
const val = literally([{ key: "a1" }, { key: "a2" }]); // Array<{key: "a1"}|{key: "a2"}>
type ValueAtKey = (typeof val)[number]["key"]; // "a1" | "a2" 🙂
The val object is the same at runtime, but the TypeScript compiler now sees it as an array of values of type {key: "a1"} or {key: "a2"}. Then the lookup done for ValueAtKey gives you the union type you're looking for.
(Note that I assume you don't care about the ordering of val here. That is, you are fine treating it as an array instead of as a tuple. Since the union type "a1" | "a2" doesn't have an inherent ordering, then the array should be sufficient.)
Hope that helps; good luck!
edited Jan 2 at 17:06
answered Jan 2 at 16:57
jcalzjcalz
30.1k22850
30.1k22850
Thatliterallyhelper is a good tip - thanks!
– Jesse Hallett
Jan 2 at 17:09
add a comment |
Thatliterallyhelper is a good tip - thanks!
– Jesse Hallett
Jan 2 at 17:09
That
literally helper is a good tip - thanks!– Jesse Hallett
Jan 2 at 17:09
That
literally helper is a good tip - thanks!– Jesse Hallett
Jan 2 at 17:09
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.
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%2f54009764%2fextract-string-union-from-array-of-objects%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
