0

I had a type, defined as such in a definition file (.d.ts) (also, the code is shortened):

type myType = {
  [key: string]: any;
  myKeyOne: string;
  myKeyTwo: number;
};

which was working fine, but for the needs of my project, I need to make these keys a little bit more dynamic since they are prone to change a lot.

So I declared some constants in a constants.ts file:

export const MY_KEY_ONE = 'myKeyOne';
export const MY_KEY_TWO = 'myKeyTwo';

and used them as such in the previous file:

type myType = {
  [key: string]: any;
  [MY_KEY_ONE]: string;
  [MY_KEY_TWO]: number;
};

But it broke all my code, stating that it

Cannot find name 'myType'

Am I not allowed to do that? Is there any way to achieve this?

Gaëtan Boyals
  • 1,193
  • 1
  • 7
  • 22
  • 1
    Seems to work https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAYwgOwM7wLIE0D6BpAUVwHkA5AuAXjgHIBbATz2AeOWBoG4AoUSWRCnRxs+IjgAqAdWJVajZgwkB3CF27cYDMMDiMJ23dQDe3OHADaAaxYAuOOigBLZAHMAuvYCGyBj3MWooQk5J4OMM5u-pZB4tLEYcgArnQARsBQPAC+PNxIaPAQ9vqGcqbmAbEhBGEARLUANGYVgbjBkjJhAAxNWUA – Titian Cernicova-Dragomir Feb 10 '23 at 13:36
  • Ah, I was so tunnel-vision that I totally forgot to check on TS Playground... So it must be the project I'm on that's configured terribly. Does not come as a surprise either lol. Thanks! – Gaëtan Boyals Feb 10 '23 at 13:41
  • Declare it 'as const' might helps : export const MY_KEY_ONE = 'myKeyOne' as const; – Romain TAILLANDIER Feb 10 '23 at 13:42
  • 1
    @RomainTAILLANDIER const declarations with literal initializers will automatically preserve the literal type without the need for `as const` – Titian Cernicova-Dragomir Feb 10 '23 at 13:43
  • Why don't you export that type and import it where you need it? – kelsny Feb 10 '23 at 14:49
  • I'm nowhere near a TypeScript pro, but I thought the whole point of having `.d.ts` files was to avoid importing/exporting types. Is it not the case? – Gaëtan Boyals Feb 10 '23 at 14:53

1 Answers1

0

Self-answer here, for those who would encounter the same "unknown" problem. This S/O thread, especially the Update (October 2020) part of the question, finally gave me the answer.

Basically, before making modifications, my definition file wasn't importing/exporting anything, making it a script and thus, making all definitions available globally. As soon as you import and/or export something, the script becomes a module and you MUST import/export anything you want to use in other files.

Gaëtan Boyals
  • 1,193
  • 1
  • 7
  • 22