Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

TypeScript: How to use a variable inferred type to define another variable with the same type, outside of a class

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...

question from:https://stackoverflow.com/questions/65831663/typescript-how-to-use-a-variable-inferred-type-to-define-another-variable-with

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...