scipper
scipper

Reputation: 3153

Get values of array of unions

Given is the following interface:

export interface ContainsArrayOfUnions {
  unionProp: Array<"TRUE" | "FALSE" | "MAYBE">;
}

Now I want to write a function with two parameters, first an array type of unionProp, the second one of the union values:

checkValue(param1: ContainsArrayOfUnions["unionProp"], param2: ???) {
  return param1.includes(param2);
}

My question

How do I create a type of the values of the union array Array<"TRUE" | "FALSE" | "MAYBE">?

EDIT Adding tsconfig.json

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es5",
    "moduleResolution": "node",
    "pretty": true,
    "allowJs": true,
    "strict": true,
    "strictNullChecks": true,
    "noImplicitThis": false,
    "noImplicitAny": false,
    "allowSyntheticDefaultImports": true,
    "noStrictGenericChecks": true,
    "skipLibCheck": true,
    "baseUrl": "./src",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "typeRoots": [
      "./node_modules/@types",
      "./src/types"
    ],
    "downlevelIteration": true,
    "resolveJsonModule": true,
    "noEmitHelpers": true,
    "importHelpers": true,
    "sourceMap": true,
    "removeComments": false,
    "lib": [
      "dom",
      "esnext",
      "esnext.array",
      "dom.iterable"
    ],
    "strictPropertyInitialization": false,
    "noErrorTruncation": true,
    "paths": {
      "@coreStyles/*": ["./src/assets/styles/*"]
    }
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

Upvotes: 0

Views: 36

Answers (1)

D Pro
D Pro

Reputation: 1776

I'd suggest

type ArrayType = "TRUE" | "FALSE" | "MAYBE";

export interface ContainsArrayOfUnions {
  unionProp: ArrayType[]
}

checkValue(param1: ContainsArrayOfUnions["unionProp"], param2: ArrayType) {
  return param1.includes(param2);
}

or using the code you already have:

checkValue(param1: ContainsArrayOfUnions["unionProp"], param2: "TRUE" | "FALSE" | "MAYBE") {
  return param1.includes(param2);
}

UPDATE: (a bit hacky, but works)

checkValue<T extends ContainsArrayOfUnions["unionProp"][0]>(param1: ContainsArrayOfUnions["unionProp"], param2: T) {
  return param1.includes(param2);
}

Upvotes: 1

Related Questions