Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Declare property as one of the values in an array

I am writing some types that will be serialized. I need to be 100% sure that a property is "one of the allowed values".

export const operationTypes = ["a", "b"]

export type Operation = {
    type: string in operationTypes // <-- this should demonstrate what I am trying to do
}

// Use this when parsing to be 100% sure that operation type is a valid string
function validateOperationType(operation: Operation) {
    return operationTypes.includes(operation.type)
}

In other words. The "type" property in Operation must be one of the values in an array. And I must be able to verify that this value actually exists in the array (at runtime).

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a const assertion on your operationTypes variable, and define the type property as typeof operationTypes[number]:

export const operationTypes = ["a", "b"] as const;

export type Operation = {
    type: typeof operationTypes[number];
}

function validateOperationType(operation: Operation) {
    return operationTypes.includes(operation.type);
}

const operation1: Operation = { type: 'a' }; // OK
const operation2: Operation = { type: 'c' }; // Error
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading