2
interface Param {name: string, age: number}

const p: Param = {name: 'tt', age: 18}

const foo = (object: {[key: string]: unknown}) => {
    // ...something
}

foo(p) 

// Argument of type 'Param' is not assignable to parameter of type '{ [key: string]: unknown; }'.
  Index signature for type 'string' is missing in type 'Param'.

The type I pass in conforms to the type of the function parameter, why am I getting an error?

Liu Kerwin
  • 21
  • 1
  • 2
  • Does this answer your question? ['unknown' vs. 'any'](https://stackoverflow.com/questions/51439843/unknown-vs-any) – jnpdx Mar 16 '22 at 05:00

2 Answers2

2

Your dynamic params should be any instead of unknown

const foo = (object: {[key: string]: any}) => {
    // ...something
}

You can check this document out for a better understanding of unknown type

[..] Much like any, any value is assignable to unknown; however, unlike any, you cannot access any properties on values with the type unknown, nor can you call/construct them. Furthermore, values of type unknown can only be assigned to unknown or any.

Which means you cannot assign values to unknown in your code

foo(p) //assign values to `unknown` type params
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • let temp: unknown temp = 123 I don't understand, why this works – Liu Kerwin Mar 19 '22 at 08:48
  • @LiuKerwin You can check this out https://mariusschulz.com/blog/the-unknown-type-in-typescript#the-unknown-type, first `unknown` type assignment is called type-correct, but for your case, you're to assign `unknown` to an existing type `Param` (similar to this case `let value: unknown; let value3: boolean = value; // Error`) – Nick Vu Mar 19 '22 at 10:31
1

This call signature provides type constraints while accepting your Param shape:

interface Param {name: string, age: number}

const p: Param = {name: 'tt', age: 18}

const foo = (object: {[key: string]: string | number}) => {
    // ...something
}

foo({...p})

As for why the spreading is needed in a literal object of the last line above:

Many objects are not iterable, including all plain objects that lack a Symbol.iterator method ... spreading in object literals enumerates the own properties of the object - Spread syntax

marckassay
  • 1,350
  • 1
  • 11
  • 19