N
N
nicknamemyy2019-04-16 12:41:18
JavaScript
nicknamemyy, 2019-04-16 12:41:18

How to describe the interface correctly in typescript?

I have an array like ['value1', 'value2', 'value3'];
you need the value to be one of what is in the array, like this:

interface MyInterface {
     name: 'значение1' | 'значение2' | 'значение3';
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
forspamonly2, 2019-04-17
@forspamonly2

generally possible. but this is not an easy question.
in the latest typescript 3.4, it became possible to put a modifier on an array , which will make it a tuple with constants. taking its type from it, it will be possible to get index type from it - the union of the names of all its fields, and then take from it the types of the fields themselves in square brackets, and all your lines will be there. on other lines it will already begin to swear. the problem is that in addition to the lines, there will also be all the methods and properties of the array. from this, the abuse will turn out to be unintelligible, and in addition to lines, for example, a number will be suitable - the length of that array. well, functions from the array prototype, although you are unlikely to assign them to your fields.as const
to leave only strings, you will also have to use conditional type (again in combination with mapped and index types): again get the full union of field names, go through all the fields, get the type, and if this is a string, take the field name, and if not - take never. and select the result already by the filtered union of field names - nothing is selected by never.

const x = ['значение1', 'значение2', 'значение3'] as const;

type AllValuesOfX = (typeof x)[keyof typeof x];

const tst1_1:AllValuesOfX = 'значение1';
const tst1_2:AllValuesOfX = 'значение4'; //error TS2322: Type '"значение4"' is not assignable to type '"значение1" | "значение2" | "значение3" | 3 | (() => string) | (() => string) | { (...items: ConcatArray<"значение1" | "значение2" | "значение3">[]): ("значение1" | "значение2" | "значение3")[]; (...items: ("значение1" | ... 2 more ... | ConcatArray<...>)[]): ("значение1" | ... 1 more ... | "значение3")[]; } | ... 1...'.
const tst1_3:AllValuesOfX = 3;
const tst1_4:AllValuesOfX = Array.prototype.map;

type StringProperties<T> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];
type StringsFromX = (typeof x)[keyof StringProperties<typeof x>];

const tst2_1:StringsFromX = 'значение2';
const tst2_2:StringsFromX = 3; // error TS2322: Type '3' is not assignable to type '"значение1" | "значение2" | "значение3"'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question