简体   繁体   English

{} 在 TypeScript 中是什么意思?

[英]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 .我在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".所以本质上,类型{}表示“不需要有任何属性,但可能有一些”,同样类型{a: string}表示“必须有一个名为a的属性,其值为string ,但可能有其他属性也”。

So {} imposes almost no constraints on its values;因此, {}对其值几乎没有任何限制; the only rule is that it can't be null or undefined .唯一的规则是它不能为nullundefined It is similar to the type object in this regard, except that object also forbids primitive values, while {} allows them:在这方面它类似于类型object ,除了object也禁止原始值,而{}允许它们:

// 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. Component<P = {}, S = {}, SS = any>表示 P 和 S 的默认类型是空对象。

So you can use the interface with 0..3 generic params like so:因此,您可以使用具有 0..3 通用参数的接口,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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