0

Is there some syntax sugar in TypeScript allows to initialize value without duplicating the expression in the right of type Type =? (Yes, semicolon must be replaced with commas)

type Type = {
    foo: "alpha";
    bravo: "bravo";
};

const value: Type = {
    foo: "alpha",
    bravo: "bravo"
};

1 Answer 1

1

If what you want is infer the type from the expression, typeof is your friend:

const value = {
    foo: "alpha",
    bravo: "bravo"
};
type Type = typeof value;

That will give you a type like:

type Type = {
    foo: string;
    bravo: string;
};

If you need to infer the every value type as a literal you can do something like:

const value = {
    foo: "alpha",
    bravo: "bravo"
} as const;

type Type = typeof value;

Now Type will be:

type Type = {
    readonly foo: "alpha";
    readonly bravo: "bravo";
};

If you don't want the properties as readonly you can do:

const value = {
    foo: "alpha" as const,
    bravo: "bravo" as const
};

type Type = typeof value;

And Type will be:

type Type = {
    foo: "alpha";
    bravo: "bravo";
};
Sign up to request clarification or add additional context in comments.

1 Comment

VERY HIGH quality answer! Thank you very much!

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.