typescript TS:函数的返回类型键入错误

m1m5dgzv  于 2023-02-13  发布在  TypeScript
关注(0)|答案(1)|浏览(147)

我有以下类型

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

ldfqzlk8

ldfqzlk81#

因为在声明返回或接收类型脚本的函数的类型时,仅当结果实际上是该类型的父类型时才进行比较,即返回的结果必须至少具有值 类型
但是当你声明const playlistPatch:时它会比较绝对值deep equal

相关问题