3

I get data from a server in the following format and I would like to define its type. I am struggling to define one of the keys as it depends on value of another key. Is it possible to define this type correctly or come a bit closer than just any?

Pseudo-code below

type Data = {
    result: string;
    url: string;
    [key: result]: { // <- ERROR. The key should be the value of the result key above. 
        message: string;
    };
};
Tomnar
  • 357
  • 2
  • 11

1 Answers1

0

Unfortunately that is not possible as you expect, because that's not why typescript is made for, Check this answer about types at runtime with typescript

Types are stripped away at compile-time and do not exist at runtime, so you can't check the type at runtime.

Personally, if you can't know the type of some property until run time, I'd suggest using Yup lazy method if you can find that possible for your case.

Louay Al-osh
  • 3,177
  • 15
  • 28
  • What you seem to be essentially saying here is that this question is a duplicate? – Liam Aug 12 '21 at 08:14
  • 1
    I'm also not really sure what this has to do with the actual question. Yes Typescript is a superset of Javascript, yes JS has no types and tyescript is compiled to JS. None of this is really relevant – Liam Aug 12 '21 at 08:15
  • He wants the types of typescript to be lazily defined at runtime based on some API return value, that is currently impossible because typescript made for author time compiling, so I made a ref to another answer because I didn't find a simple duplicated question, and give a suggestion that he can choose for himself if that is feasible or not. – Louay Al-osh Aug 12 '21 at 08:19