Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a typescript definition that depends on previous value?

See this code for example:

var a
a.set('my-custom-value',55)
a.

In line number 3, How I make the IDE to be aware to the value in line 2, and offer auto complete to a string the defined by the end-user who is using the library?

I want that after I type a. I will see "my-custom-value" as an auto-complete option by VSCode.

I saw the yargs is working like that. If I defining a option or a positional parameter, later the IDE offer me what I choosed.

like image 433
Aminadav Glickshtein Avatar asked Mar 02 '23 02:03

Aminadav Glickshtein


1 Answers

This can be done with an asserts return type, which is possible because Typescript supports control-flow type narrowing:

class Foo {
    setKey<K extends PropertyKey, V>(k: K, v: V): asserts this is Record<K, V> {
        (this as any)[k] = v;
    }
}

let foo: Foo = new Foo();
// foo. completes as foo.setKey

foo.setKey('bar', 23);
// now foo. completes as foo.bar or foo.setKey

Playground Link

like image 96
kaya3 Avatar answered Mar 05 '23 00:03

kaya3