我有以下类型
export interface BackupItems {
Playlist: {
playlistItemList?: string[];
};
}
export type BackupItemPatch<T extends keyof BackupItems> = BackupItems[T];
- 正确 * 检查
BackupItemPatch<'Playlist'>
类型的元素(BackupItemPatch<'Playlist'>
没有属性id
):
const playlistPatch: BackupItemPatch<'Playlist'> = {
playlistItemList: [],
id: '1', // ~~~error~~~
};
有误差
Type '{ playlistItemList: undefined[]; id: string; }' is not assignable to type '{ playlistItemList?: string[]; }'.
Object literal may only specify known properties, and 'id' does not exist in type '{ playlistItemList?: string[]; }'.(2322)
当
const patchPlaylist: () => BackupItemPatch<'Playlist'> = () => {
return {
playlistItemList: [],
id: '1',
};
};
不会给出任何错误,尽管patchPlaylist
的返回类型也是BackupItemPatch<'Playlist'>
类型。
请注意,如果我省略playlistItemList
属性,则会得到一个错误:
Type '() => { id: string; }' is not assignable to type '() => { playlistItemList?: string[]; }'.
Type '{ id: string; }' has no properties in common with type '{ playlistItemList?: string[]; }'.(2322)
同样,如果playlistItemList
的类型错误(比如一个数字数组):
Type '() => { playlistItemList: number[]; id: string; }' is not assignable to type '() => { playlistItemList?: string[]; }'.
Call signature return types '{ playlistItemList: number[]; id: string; }' and '{ playlistItemList?: string[]; }' are incompatible.
The types of 'playlistItemList' are incompatible between these types.
Type 'number[]' is not assignable to type 'string[]'.
Type 'number' is not assignable to type 'string'.(2322)
但是为什么我可以添加BackupItem<'Playlist'>
上不存在的属性?StackBlitz
1条答案
按热度按时间ldfqzlk81#
因为在声明返回或接收类型脚本的函数的类型时,仅当结果实际上是该类型的父类型时才进行比较,即返回的结果必须至少具有值 类型
但是当你声明
const playlistPatch:
时它会比较绝对值deep equal