Home > Mobile >  Declare property as one of the values in an array
Declare property as one of the values in an array

Time:06-13

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?

CodePudding user response:

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
  • Related