type TField = {
field1: string;
field2: boolean;
field3: TMyCustom;
}
class Test1 {
// I opt for using TypeScript's index signature to declare class fields
[key: keyof TField]: TField[typeof key]
// Instead of individually declaring each field...
// field1: string;
// field2: boolean;
// field3: TMyCustom;
constructor() {
// TypeScript cannot infer from the index signature
// Error : Property 'field1' does not exist on type 'Test1'
this.field1 = 'initialField1'
// Error : Property 'field2' does not exist on type 'Test1'
this.field2 = true;
// Error : Property 'field3' does not exist on type 'Test1'
this.field3 = '';
}
}
I am exploring the possibility of declaring class fields using TypeScript's index signature.
In the provided example, I positioned class Test1 alongside TField to streamline my process.
However, in my project codebase, importing TField from multiple files poses a challenge. This restricts me from manually declaring fields of Test1 one by one.
I'm uncertain whether my approach to writing a TypeScript index signature is incorrect or if TypeScript does not support this specific type usage.
----------- updated question
type TField = {
field1: string;
field2: boolean;
field3: TMyCustom;
}
class Test0 {
// Previously, I defined the property "fields" with a type of TField
fields: TField
// Now, I aim to directly declare and access field1,2,3 at the class property level,
// without nesting them within the "fields" property.
constructor() {
this.fields = {
field1: 'initial field1',
field2: true,
field3: {some: 'object'} as TMyCustom,
}
}
}
Prior to attempting an index signature conversion, my code resembled the structure of the Test0 class.
I understand there may be curiosity regarding why I chose to assign the field1,2,3 inside the "fields" property rather than directly as class properties. However, this decision is linked to the project's design constraints, so please set aside that inquiry.
Because field1,2,3 are nested within the fields property, I must access them like this test0Instance.fields.field1
Therefore, I pose the question of whether it's feasible to use an index signature to define class fields