Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript restrict type with no properties from accepting strings or arrays

Tags:

typescript

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

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

function baz(param: foo) {
}

baz("hello");
like image 571
MichaelAttard Avatar asked Mar 03 '17 16:03

MichaelAttard


1 Answers

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.

like image 68
Saravana Avatar answered Sep 22 '22 18:09

Saravana