Andreas Frische
Andreas Frische

Reputation: 9891

can Typescript express "a is some object"?

In the following snippet, can TypeScript express "a is some object, but not Boolean, Number,String,Array or a function" ?

var a:Object;
a = {
    just: "some object",
    n: 1,
};
// what type does `a` need to disallow the following
a = ["array", 2, {}];
a = "nostring";
a = false;
a = 0;
a = ()=> { return "i am a function!"};
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(a.toString());
};

document.body.appendChild(button);

Upvotes: 0

Views: 81

Answers (3)

Ernesto
Ernesto

Reputation: 4272

Create your own ObjectLiteral interface

export interface ObjectLiteral {
   [prop: string]: any
}

const a: ObjectLiteral = {
    just: "some object",
    n: 1,
};

enter image description here

Upvotes: 0

thoughtrepo
thoughtrepo

Reputation: 8383

This works... but please don't actually use this. Types should define what something is, not what it isn't.

interface Array<T> { notArray: void; }
interface String   { notString: void; }
interface Boolean  { notBoolean: void; }
interface Number   { notNumber: void; }
interface Function { notFunction: void; }

interface GuessWhatIam {
    notArray?: string;
    notString?: string;
    notBoolean?: string;
    notNumber?: string;
    notFunction?: string;
    [key: string]: any;
}

var a: GuessWhatIam;

Upvotes: 1

basarat
basarat

Reputation: 275927

a is some object, but not Boolean, Number,String,Array or a function

No.

Workaround

Only allow the types you want to allow (instead of catchall Object). You can use a union type if you want to e.g.:

// Only allow the things you want: 
let b : {
    just:string;
    n: number
} | {
    foo:string;
    bar: string;
};

b = {
    just: "some object",
    n: 1,
};

b = {
    foo: 'hello',
    bar: 'world'
}
// All the following are errors: 
b = ["array", 2, {}];
b = "nostring";
b = false;
b = 0;
b = ()=> { return "i am a function!"};

Upvotes: 1

Related Questions