0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, It should be type rather than const. I edited the post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.