How do you type an object that can have both a few declared optional properties, e.g.:
{
hello?: string,
moo?: boolean
}
as well as custom properties (that must be functions), e.g.:
[custom: string]: (v?: any) => boolean
This is what I'd like to see for example:
const myBasic: Example = {moo: false}
// -> ✅ Valid! Using known keys
const myValid: Example = {hello: 'world', customYo: () => true}
// -> ✅ Valid! "customYo" is a function returning a bool. Good job!
const myInvalid: Example = {hello: 'world', customYo: 'yo!'}
// -> ☠️ Invalid! "customYo" must be a function returning a boolean
Trying to add an index signature to an interface with known keys (i.e. hello?: string, moo?: boolean
) requires all keys to be subsets of the index signature type (in this case, a function returning a boolean
). This obviously fails.
This is not possible, by design https://basarat.gitbooks.io/typescript/docs/types/index-signatures.html
The only way to get around it is to exploit that each interface can have 2 separate index signatures, one for
string
andnumber
In you example
hello
andmoo
make the string index unusable, but you can hijack the number index for the custom methodsThis works but is hardly an acceptable interface as would lead to unintuitive functions and you would have to call them by array notation
This also has the caveat that the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, javascript will convert the number to a string before indexing into an object
In this case you have no explicit string indexer, so the string index type is the default
any
which the numeric indexer type can conform toIMPORTANT This is just for the science, I don't recommend this as a real life approach!