#How do I accept a key/value pair as an argument to a class method?

38 messages · Page 1 of 1 (latest)

dim shore
#

This code is throwing an error for some reason:

magicWand([key: string]: Function) {

    }
lost juniper
#

uh yeah because that's not valid

#

what are you trying to do?

dim shore
#

Why's that?

lost juniper
#

...i don't even know how to explain that. why do you think it's valid

dim shore
#

I'm new to Typescript, in my head I was passing a key that was of type value and a pointer to a function.

lost juniper
#

separate parameters are separated by ,

#

[K: string]: Function is wrapped inside an object there, that's what makes that valid, it's an index signature

#

what kind of input are you expecting with this

dim shore
#

So I tried making it an object and it still didn't play nice.

#

I'm trying to replicate the symbol table from the post above.

#

The first answer.

lost juniper
#
const magicWand: { [K: string]: Function }
//    ^ name     ^ type
//                 ^ index signature, part of the type
#

do you know js?

dim shore
#

Yeah.

lost juniper
#

try writing it out in js first

#

then add types

dim shore
#

so a class method?

lost juniper
#

yeah, start with minimal types

#

write it out as you would in js

dim shore
#

magicWand(pair) { // body }

#

pair being an object parameter I guess.

#

Is it perhaps an interface that I need to define?

lost juniper
#

right, so now add type annotations to that method

dim shore
#

magicWand(pair: object) { // body }

lost juniper
#

no, that's not correct

#

you want pair to be a specifc shape here, so you have to specify that

dim shore
#

magicWand(pair: {key: string, func: Function}) { // body }

terse edge
#

where did pair go :(

dim shore
#

I guess I'm unsure how to annotate sub-properties of an argument.

terse edge
#

!hb object types

modern apexBOT
dim shore
#

Ah cool.

#

oh my god

#

okay i know what i did wrong

#

thanks for the help