1

I have a predefined object:

const obj = {
  ONE: 'ONE',
  TWO: 'TWO'
};

I want to define assign the constant obj.ONE to a new type like this:

type TOne = obj.ONE

I get the following warning: Cannot find namespace 'obj'. or 'ONE' refers to a value, but is being used as a type here. if I don't put the strings inside an object. Is there a fix around this to allow me to assign a predefined string to a type?

8
  • 1
    You're looking for typeof obj.ONE Commented May 10, 2020 at 13:09
  • @CertainPerformance that would assign the type string to TOne, but I want type "ONE" Commented May 10, 2020 at 13:13
  • If you can't control how the object is defined, then you can't get to 'ONE' due to automatic type widening Commented May 10, 2020 at 13:14
  • 2
    If you can control where it's defined, declare the object as const, or as 'ONE' in the property definition. Otherwise, you're out of luck Commented May 10, 2020 at 13:20
  • 1
    Works fine here: typescriptlang.org/play?#code/… Commented May 10, 2020 at 13:35

1 Answer 1

2

Usually, to extract the value of a property from an object, you can use typeof, eg:

const TOne = typeof obj.ONE;

But, in object literals, Typescript automatically widens the types of the values by default, unfortunately, so

const obj = {
  ONE: 'ONE',
  TWO: 'TWO'
};

results in an obj of type

{
  ONE: string;
  TWO: string;
}

The 'ONE' string type is lost. You can avoid the type widening by declaring the object as const, or by declaring the property as const or as 'ONE':

const obj = {
  ONE: 'ONE',
  TWO: 'TWO'
} as const;
const obj = {
  ONE: 'ONE' as 'ONE',
  TWO: 'TWO'
};
Sign up to request clarification or add additional context in comments.

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.