Is there a way to define a type excludes Function from Record<string, any>?

Issue

I have a collector function like

const track = (data: Record<string, any>) => {
  //...
}

and some data generators like

const genData = () => ({
  name: 'x'
})

Currently the track function could accept genData() and genData as parameter without warning, and it is likely to make some mistakes.

So how to throw warning when accept a Function?

Solution

You can apply validator which forbids an argument if it will be a function:

type NotFn<T extends Record<string, any>> =
    T extends (...args: any[]) => any ? never : T

const track = <
    Data extends Record<string, any>
>(data: NotFn<Data>) => { }

const genData = () => ({
    name: 'x'
})

track(genData)

Playground

You can find more information about TS negation in my article

Answered By – captain-yossarian from Ukraine

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.