简体   繁体   中英

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> { }

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 asssignable 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

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, []>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM