0

I'm tryining get all defined types from variable in construct.

export interface TestType {
  resultType?: 'NUMBER' | 'STRING' | 'DATE' | 'ENUM' | 'AMOUNT' ;
}

And I expect the result of something like this.

const types: string[] = ['NUMBER', 'STRING', 'DATE', 'ENUM', 'AMOUNT'];

There may be a function or ability to achieve this from constructor. When the contrustor cannot be changed?

I try to automate it so that it basically extracts all types and I was able to get them to select.

Here is just one example that this is not possible.

Or ideas for similar solutions?

Actual I am currently using Typescript in v4.0.5

Thanks.

0

2 Answers 2

0

If what you want is something similar to iterate over possible values of a variable. Types need to be refered to in a static final way in typescript.

export class TestClass{
    types = ['NUMBER', 'STRING', 'DATE', 'ENUM', 'AMOUNT'] as const;
    resultType: TestClass["types"][number];
}

In the above example the accepted values of resultType are members of the types Array. So type validation will trigger.

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

Comments

0

As these types do not exist at runtime, you cannot generate the strings directly. You could create some helper that will ensure that you use only the right keys.

type Types = 'foo'|'bar'|'baz';

type TypeHolder<T extends string> = { [Key in T]: number; }

function getKeys<T extends string>(types: TypeHolder<T>) {
    return Object.keys(types);
}

console.log(getKeys<Types>({ foo: 1, bar: 1, baz: 1 }));  // ['foo', 'bar', 'baz']

Hmm, not really nice. It's probably much easier to do it the other way around:

const types = ['foo', 'bar', 'baz'] as const;
type Types = typeof types[number];   // 'foo'|'bar'|'baz'

Comments

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.