Typescript: index signatures in mapped type

How can I take the type { 'k': number, [s: string]: any } and abstract over 'k' and number? I would like to have a type alias T such that T<'k', number> gives the said type.


Consider the following example:

function f(x: { 'k': number, [s: string]: any }) {}                           // ok
type T_index_only = { 'k': number, [s: string]: any };                        // ok
type T_key_only<k extends string> = { [a in k]: number };                     // ok
type T_key_and_index<k extends string, V> = { [a in k]: V, [s: string]: any };// ?
  • Using { 'k': number, [s: string]: any} directly as type of the parameter of the function f works.
  • Using the [s: string]: any indexed part in type-alias works
  • Using k extends string in type-alias also works
  • When combining the k extends string with the [s: string]: any in same type-alias, I get a parse error (not even a semantic error, it doesn't even seem to be valid syntax).

This here seems to work:

type HasKeyValue<K extends string, V> = { [s: string]: any } & { [S in K]: V }

but here, I can't quite understand why it does not complain about extra properties (the type on the right side of the & should not allow objects with extra properties).


I've seen the questions

but those did not seem directly related, albeit having a similar name.



from Recent Questions - Stack Overflow https://ift.tt/33kvqbR
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)