繁体   English   中英

打字稿:类型交集和类型别名出现问题

[英]Typescript: issue with type intersection and type alias

使用Typescript 2.1.4 ,在使用交集类型( type1 & type2 )和类型别名( type Something<T> = ... )时遇到了一些奇怪的编译问题。

为了解释我试图达到的目的:我只想声明一个类型别名,该别名表示一些定义的对象值(在这种情况下为string类型的属性id )与自定义其他属性的交集,它们都是可选的。 此类型使用Typescript预定义的Partial类型别名。

以下代码可以编译和运行:

export type StoreModelPartial<T> = {id:string} & T;

function test<T>(obj:StoreModelPartial<T>) {
    console.log('TEST', obj);
}

console.log(test({
    'id':'value',
    'something':'value2'
}));

但是,当我尝试使用Partial类型别名时,出现编译错误:

export type StoreModelPartial<T> = Partial<{id:string} & T>;

function test<T>(obj:StoreModelPartial<T>) {
    console.log('TEST', obj);
}

console.log(test({
    'id':'value',
    'something':'value2'
}));

我收到此错误:

类型'{'id'的参数:字符串; 'something':字符串; }”不能分配给“ Partial <{id:string; }&T>

任何想法?

啊,算了吧,我想我是通过写这个问题来解决的……然后重新阅读我的代码示例的错误消息,这比我最初处理的更复杂的部分更清楚。

我以为交集和扩展名有些相同,但是不行。

我需要的是extends

export type StoreModelPartial<T extends {id?:string}> = Partial<T>;

function test<T>(obj:StoreModelPartial<T>) {
    console.log('TEST', obj);
}

console.log(test({
    'id':'value',
    'something':'value2'
}));

暂无
暂无

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

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