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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…