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

Time:06-09

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?

CodePudding user response:

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

CodePudding user response:

If you want to only allow objects but don't know the type of the values, you can use Record<string, unknown>.

const track = (data: Record<string, unknown>) => {}

track(genData)
// Error: Index signature for type 'string' is missing in type '() => { name: string; }'

Playground

  • Related