#How to define specific return type for known args?

20 messages · Page 1 of 1 (latest)

leaden bear
#

Let's say I've got this method obj.getProperty(key) where the type for each property depends on the specific key.

How can I define the type (specifically in a .d.ts file) so that known keys return defined types, but the rest return unknown?

So basically

interface Obj {
  getProperty('foo'): Foo;
  getProperty('bar'): Bar;
  getProperty(key: string): unknown;
}
spiral kraken
#

you almost had the right syntax

#

@leaden bear

#

don't forget the parameters do need names

#

so that would give something like

interface Obj {
    getProperty(key: 'foo'): Foo;
    getProperty(key: 'bar'): Bar;
    getProperty(key: string): unknown;
}
#

this is called an overload btw, you can find those in the docs

#

!hb overload

thorn pastureBOT
leaden bear
#

!resolved

#

p.s. It looks like the most-generic definition has to be first, VS Code is complaining about the "unknown" usages otherwise.

spiral kraken
#

the most precise definitions have to go first

#

VS Code is complaining about the "unknown" usages otherwise.
are you sure your parameter is typed as "foo" and not as string when passed to the function?

leaden bear
#

That's what it gives me when I put the most-specific first

#

Where the right is my .d.ts file

spiral kraken
#

don't think the syntax is right

leaden bear
#

Ok nevermind, all solved now, yeah I just realized I used the completely wrong syntax on the right

spiral kraken
#

declare is usually used for 1 object at a time, not sure it works with overloads