type someType = {
keyOne: string,
keyTwo: string,
};
type someOtherType = {
keyOne: string,
keyTwo: string,
keyThree: string,
};这两种类型都是包含keyOne和keyTwo的对象,唯一的区别是后者用keyThree的附加键扩展了前者。
与编写重复的代码不同,是否可以通过扩展someOtherType来构建someType流类型?在我的脑海中,ES6对象rest/spread出现在我的脑海中,但我不知道如何在流中完成这样的任务。
谢谢!
发布于 2017-03-07 00:15:33
你要找的是相交类型。根据文件:
交类型要求值为所有输入类型。 语法:交集:< type 1>&< type 2>.&;type n>
交集类型的目的是扩展现有类型并向其添加其他类型要求。
type someType = {
keyOne: string,
keyTwo: string
}
type someOtherType = someType & {
keyThree: string
}
const shouldBeOk: someOtherType = {
keyOne: 'biz',
keyTwo: 'buzz',
keyThree: 'baz',
}
const shouldError: someOtherType = {
keyOne: 123,
keyTwo: 'hello',
keyThree: 'world',
}
// flow error:
16: const shouldError: someOtherType = {
^ object literal. This type is incompatible with
8: type someOtherType = someType & {
^ object type交集类型的逻辑对立面是联合型。根据文件:
联合类型要求值是输入类型之一。 语法: Union:< type 1> type < type 2>.
作为一个例子。可以使用联合类型创建可枚举的。
type fooBarBazType = 'foo' | 'bar' | 'baz';
const shouldBeOk: fooBarBazType = 'bar';
const shouldError: fooBarBazType = 'buzz';
4: const shouldError: fooBarBazType = 'buzz';
^ string. This type is incompatible with
4: const shouldError: fooBarBazType = 'buzz';
^ string enum发布于 2019-04-14 08:33:54
https://stackoverflow.com/questions/42582880
复制相似问题