Flare
Flare

Reputation: 83

How to enforce a curly braces ONLY object in typescript?

Hi I'm trying to make a function that only takes in an object that has a key-value pair object put in this specific form only:

{ key: value } Where key or value can be anything. as long as it is in curly braces.

I don't want to accept any other value that doesn't have the curly brace format. Here is a basic example of what I'm trying to accomplish:

// What do I put as the type for "param"?
function func(param: object) {

}

func({ hello: "world" }) // <-- I only want this one to work
func([1,23,4])           // this shouldn't work

class T {}

func(T)                  // This shouldn't work as well
func(new T())            // Neither should this
func(function() {})      // Neither should this

What type would I need to put into params to only accept an object with the curly braces format?

Upvotes: 0

Views: 109

Answers (1)

Flare
Flare

Reputation: 83

Thanks to Dilshan for the answer:

function func(param: Record<string, unknown>) {
}

More info on Record: Record<Keys, Type>

What I was doing wrong here was I was using Record<string, any> instead of unknown when I was experimenting with Record.

Upvotes: 1

Related Questions