8

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

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

function baz(param: foo) {
}

baz("hello");
3
  • 1
    Why do you care? If it fits your interface, why do you mind whether it's a string or an object? Commented Mar 3, 2017 at 16:47
  • 2
    We had a bug where we were passing the object's property instead of the object, and typescript compiled fine. Commented Mar 3, 2017 at 17:01
  • That is a valid concern. Commented Mar 3, 2017 at 17:02

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Isn't that cheating a bit? You are forcing that the parameter has to be an object.
@MuratK.: Isn't that what the OP wants? But I would lean toward not making it a type, just function baz(param: foo & object)
Worth noting that the object type is very new, you'll need TypeScript 2.2 to use it.
Nice one, is there a type that allows objects apart from array?
@user3233089 yes, for some definition of array: interface NotAnArray { forEach?: void }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.