MichaelAttard
MichaelAttard

Reputation: 2158

Typescript restrict type with no properties from accepting strings or arrays

Is it possible to restrict param not to accept strings, arrays etc.?

interface foo {
    a?: number;
    b?: string;
}

function baz(param: foo) {
}

baz("hello");

Upvotes: 8

Views: 524

Answers (1)

Saravana
Saravana

Reputation: 40544

You can do something like this to make baz accept at least an object:

interface foo {
    a?: number;
    b?: string;
}

interface notAnArray {
    forEach?: void
}

type fooType = foo & object & notAnArray;

function baz(param: fooType) {
}

baz("hello"); // Throws error
baz([]); // Throws error

fooType here is an Intersection Type.

Upvotes: 5

Related Questions