1

Here is the javascript code:

const obj = {
  result: {},
  add(key, value) {
    this.result[key] = value;
  }
};

obj.add('test', 1);

How to write a typescript declaration for obj to let vscode know that now obj.result has a property named "test" whose type is number?

1 Answer 1

1

you probably can't (i'm unaware of constructs that can achieve this in v3.8), there is not ts-type information in runtime (if you want to determine type of result property based on calls of add function).

what you can do is create generic definition of obj that ties value argument type to result property structure.

type MyType<T> = {
  result: Record<string, T>;
  add: (key: string, value: T) => void;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.