aztack
aztack

Reputation: 4594

How to get readonly-item type from an array in TypeScript?

How to get readonly item array from an array constant?

const const basicValueTypes = [{
  value: 'number',
  label: 'Number'
},{
  value: 'boolean',
  label: 'Boolean'
}];

type ReadonlyItemArray = ???

type ReadOnlyBasicValueTypes = ReadonlyItemArray<typeof basicValueTyeps>;
/*
↓↓↓↓
ReadOnlyBasicValueTypes = (
  {value: 'number', label: 'Number'}
| {value: 'boolean', label: 'Boolean'}
)
*/

Update: I figure out that I can make every item as const:

const basicValueTypes = [{
  value: 'number',
  label: 'Number'
} as const,{
  value: 'boolean',
  label: 'Boolean'
} as const];

type BasicValueTypes = typeof basicValueTypes[number]['value'];
// BasicValueTypes = "number" | "boolean"

But I still want to know is it possible to contrive above ReadonlyItemArray type?

Upvotes: 0

Views: 1176

Answers (1)

To make basicValueTypes immutable (readonly), you can use as const.


const basicValueTypes = [{
    value: 'number',
    label: 'Number'
}, {
    value: 'boolean',
    label: 'Boolean'
}] as const;

To get the type, you can use typeof:

type Immutable = typeof basicValueTypes

To make literal type, you can use :

type Literal = [number, string]

Also there is built in readonly array:

type Arr = ReadonlyArray<string>

const arr:Arr=['a','b']
arr.push('c') // error

But you can't do smth like that:

const ReadOnlyBasicValueTypes = ReadonlyItemArray<typeof basicValueTyeps>;

BEcause types are not constructors, like it is in F#, it is only types. TS compiler will remove them from source code, and you will receive pure js

Update

 const basicValueTypes = [{
  value: 'number',
  label: 'Number'
},{
  value: 'boolean',
  label: 'Boolean'
}] as const;

type Basic = typeof basicValueTypes;
type Item = Basic[number] // check this type

Upvotes: 2

Related Questions