sunknudsen
sunknudsen

Reputation: 7290

What does {} mean in TypeScript?

I am guessing it means empty object, but not sure...

I can’t find that type on https://www.typescriptlang.org/docs/handbook/basic-types.html.

interface Component<P = {}, S = {}, SS = any> extends ComponentLifecycle<P, S, SS> { }

Upvotes: 2

Views: 4285

Answers (2)

kaya3
kaya3

Reputation: 51083

The type {} does not exactly mean an "empty object", because other types of object - which may not be empty - are assignable to the type {}. For example:

function acceptsEmpty(obj: {}): void {
    console.log(obj);
}

let notEmpty: {a: string} = {a: 'test'};

// no error; {a: string} is assignable to {}
acceptsEmpty(notEmpty);

So essentially, the type {} means "not required to have any properties, but may have some", and likewise the type {a: string} means "must have a property named a whose value is a string, but may have other properties too".

So {} imposes almost no constraints on its values; the only rule is that it can't be null or undefined. It is similar to the type object in this regard, except that object also forbids primitive values, while {} allows them:

// no error
let anything: {} = 1;

// error: Type '1' is not assignable to type 'object'.
let noPrimitivesAllowed: object = 1;

Playground Link

Upvotes: 8

Andreas Dolk
Andreas Dolk

Reputation: 114797

Component<P = {}, S = {}, SS = any> means that the default types for P and S are empty objects.

So you can use the interface with 0..3 generic params like so:

const a: Component  // = Component<{},{},any>
const b: Component<SomeType>  // = Component<Some,{},any>
const c: Component<SomeType, SomeOtherType>  // = Component<SomeType, SomeOtherType, any>
const d: Component<SomeType, SomeOtherType, []>  // = Component<SomeType, SomeOtherType, []>

Upvotes: 2

Related Questions