0

我有一个字典接口,我希望索引类型为字符串,值为字符串类型。

interface One {
 [key: string]: string;
}

如果我将此类型注释为一个包含没有属性的对象的常量变量,那么它不会给我一个错误。

const example: One = {}; // no error why?

上述方法的另一个问题是const example = {} as One;这也有效。

如果我不提供对象的索引签名,那么它会给我一个错误,即您缺少属性。

interface Two {
 first: string;
 second: string;
}

const example2: Two: {}; // error missing properties
// to tackle this situation I used type assertion

const example3 = {} as Two; // no error

我的问题是为什么example变量接受没有属性的对象?

你可能有一个问题,为什么我想要一个没有属性的对象。原因是我想稍后向那个空对象添加一些属性。在那种情况下,我应该做类型断言还是类型注释?

4

1 回答 1

1

在第一个示例中,您只是定义了索引的类型,并没有像使用 in 那样指定索引:

type Keys = 'first' | 'second'
type One = { [P in Keys]: string };

const one: One = {}; // Error: Type '{}' is missing the following properties from type 'One': first, second

在第二个示例中,您断言该值为Two。您是在告诉 typescript 信任您。如果要使用Two类型但使字段可选,则可以使用Partial实用程序类型。

const example2: Partial<Two> = {}; // valid
const example3: Partial<Two> = { first: '1' }; // valid
const example3: Partial<Two> = { third: '3' }; // Error: Object literal may only specify known properties.
于 2021-08-12T13:59:33.527 回答