11

I have function using an object as parameter like this:

interface Options {
    foo?: string;
    bar?: number;
};

function fooNction(opts: Options): void {
}

This works fine in some cases but not all:

fooNction({foo: "s"});   // OK
fooNction({a: "x"});     // fine as TS gives an Error as expected
fooNction("hello");      // no Error...

I tried to extend my interface from TS 2.2 object type like this

interface Options extends object {
    foo?: string;
    bar?: number;
};

to disallow basic types but typescript tells "Cannot fine name 'object'".

Is there any way to define an interfaces has to be an object but has no mandatory field?

1 Answer 1

12

For some reason, it's not allowed to have an interface that extends built-in type like object or string. You may try to bypass that by declaring type alias for object like this

type ObjectAlias = object;

interface Options extends ObjectAlias {
   ...
}

but it still does not work because structural compatibility is used for typechecking interfaces:

function fooNction(opts: Options): void {
}

fooNction("hello"); //ok

So it seems like object is usable only with intersection types, and you must declare Options as a type, not an interface to make it work:

type  Options = object & {
    foo?: string;
    bar?: number;
};

function fooNction(opts: Options): void {
}

fooNction("hello"); //error
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.