1

Let's say I have this variable:

const x = {
  name: 'shachar',
} as const;

This variable has the inferred type of

{
  name: 'shachar';
}

I want to use that type to create another type alias like this:

const y: {[key in keyof *TYPE_OF_X*]: boolean} = {
  name: true;
}

Without having to define this type explicitly.

This can be done if I was inside a class:

class MyClass {
  x = {
   name: 'shachar',
  } as const;

  y: {[key in keyof this['x']]: boolean} = {
    name: true;
  }
}

But can this be done if I'm outside a class?

I've also found the following workaround:

class MyClass {
    x = {
      name: 'shachar',
    } as const;
}

const x = (new MyClass()).x;

const y: { [key in keyof MyClass['x']]: boolean} = {
    name: true,
}

But it doesn't look really good, it requires me to add a redundant class, and might make the code look messy when I repeat this method over and over...

1 Answer 1

1

Your pseudocode is already very close, using key in keyof typeof x will work as expected:

const x = {
  name: 'shachar',
} as const;

const y: {[key in keyof typeof x]: boolean} = {
  name: true,
};
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.