2

I'm using typescript in jsdoc, and am trying to constrain a variable to one of a known set of values that I have in an array.

I know I can do it like this:

/** @type {'one'|'two'|'three'} */
let v = 'four';
// ==> Error, type 'four' is not assignable to type 'one'|'two'|'three'

In my case, I have the desired values nearby in an array. To avoid retyping, I'd like to somehow reference them, but I don't know if it's possible. I'd like something like this:

const OPTIONS = ['one', 'two', 'three'];

/** @type {string<Options>} */
let v = 'four';
// ==> Desired -- Error, type 'four' is not assignable to type 'one'|'two'|'three'
// ==> but that doesn't actually work...

Is there some way to do this?

2 Answers 2

8

As Augusts 28, 2021, It's possible using JSDoc inline @type {const} like following:

const OPTIONS = /** @type {const} */ (['one', 'two', 'three']);

/** @type {typeof OPTIONS[number]} */
let v = 'four'; 
//  ^ error: Type '"four"' is not assignable to type '"one" | "two" | "three" | 

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

Comments

3

I don't think you can achieve that with an array, as they are mutable in runtime:

const OPTIONS = ['one', 'two', 'three'];
OPTIONS[0] = 'BOOM';

You can, however, change an array to a tuple (tuples are immutable):

const OPTIONS = ['one', 'two', 'three'];                
const OPTIONS_TUPLE = ['one', 'two', 'three'] as const;

Compare inferred types:

// const OPTIONS: string[]
// const OPTIONS_TUPLE: readonly ["one", "two", "three"]

Now, you can retrieve the type you want:

const OPTIONS_TUPLE = ['one', 'two', 'three'] as const;
type OptionsValue = typeof OPTIONS_TUPLE[number];
const x: OptionsValue = 'four'; 
//TS2322: Type '"four"' is not assignable to type '"one" | "two" | "three"'.

1 Comment

Thanks, really helpful. Unfortunately it looks like as const is not currently available in jsdoc syntax, but i'll keep an eye on this for down the road. github.com/Microsoft/TypeScript/issues/30445 Leaving question open for a while in case there are other suggestions that are currently possible.

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.