So from:
export interface Category{
val: string;
icon: string
}
const categoryArray: Category[] = [
{
val: 'business',
icon: 'store'
},
{
val: 'media',
icon: 'video'
},
{
val: 'people',
icon: 'account'
},
...
I'd like to get a Union type back like this:
'business' | 'media' | 'people' ...
I don't know what kind of syntax or helpers there are for this, maybe none at all. I realise this way might be backwards, and should perhaps use an Enum, but before that, I want to know it it's possible.
Some fictional examples of what I'd like to do, but the solution I expect to be more complex
type Cats = keysof[] categoryArray 'val'
type Cats = valuesof categoryArray 'val'
The following is close, but returns string
:
export type CatsValType = typeof categories[number]['val']
Or the following; instead of the types I need the string literals
type ValueOf<T> = T[keyof T];
type KeyTypes = ValueOf<typeof categories[number]> // Returns: `string`
There are similar questions like: Is there a `valueof` similar to `keyof` in TypeScript? but they don't assume an array of objects.
And the example here: https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html is similar, but I don't want to return the type, but the value of the fields, so I get a Union type back.
Category
becomes readonly and mandatory. I didn't include any optional in the example, but let's say I have adisabled?: boolean;
there, it will error:Property 'disabled' does not exist on type '{ readonly val: "art"; readonly... etc.
– Wes