1

I have a generic function which is supposed to broadcast the contents of a given type to whoever cares to receive it.

something like

function broadcast(J:Record<string,unknown>){...}

but when I got to apply a specific type to that function I get an error e.g.

interface foo
{
   thing: string;
}

const a:foo={thing:'wow'};

broadcast(a); // error that I am not using a specific type but broadcast doesn't care.

I have figured out I can unwrap the type like so:

broadcast((a as unknown) as Record<string,unknown>) 

but I think there is a better way.

2 Answers2

1

The below should work, instead of unknown, pass Record an argument of type T. Also you don't even need an interface foo.

function broadcast<T>(J : Record<string,T>){
    console.log(J)
}

const a = {thing:'wow'};

broadcast<string>(a); 
msapkal
  • 8,268
  • 2
  • 31
  • 48
0

In your example, you don't actually need a foo interface as it generates no value helping you keep your code type-safe.

The core issue with your code is the use of type unknown, anything can assign to unknown but unknown can't assign to anything but itself.

This is why your foo interface typed variable a can't be assigned to a parameter expecting Record<string, unknown>.

Replace it with Record<string, any> will make typescript happy again.

However, as I said earlier this extra interface guard foo generates no value so you might just consider remove it.

Xinan
  • 3,002
  • 1
  • 16
  • 18
  • Thanks! The points was that broadcast wants a record type, foo is a kind of record type, but I don't want the TS linter complaining or the need to remove type checking completely (e.g. integers don't belong in broadcast). The use of a generic type was what I was thinking should work but I couldn't figure out the syntax to make it work. I think Mahesh answered the question. – RУап GRΟТН May 04 '20 at 01:35