SuspiciousLookingOwl / youtubei

Get Youtube data such as videos, playlists, channels, video information & comments, related videos, up next video, and more!
https://suspiciouslookingowl.github.io/youtubei
MIT License
240 stars 50 forks source link

Type confusion when getting playlist video items #89

Closed aervxa closed 10 months ago

aervxa commented 10 months ago

Is your feature request related to a problem? Please describe. Its getting in my head when typescript gives me the error: Property 'items' does not exist on type 'PlaylistVideos | VideoCompact[]' Yes, it doesn't, but the type is always returned as PlaylistVideos and never have I got a VideoCompact[] type from .getPlaylist().videos

Describe the solution you'd like Give the videos object the PlaylistVideos type

Describe alternatives you've considered When I want to get videos.items I use this code

// type PlaylistVidoes is imported from "youtubei"
((await youtube.getPlaylist().videos) as PlaylistVideos).items

Additional context maybe there is a scenario where VideoCompact[] can be the type, but so far, I haven't. If it can, then this feature request is just a shortcoming on my end.

aervxa commented 10 months ago

Or you could do this

// 'url' is a playlist string
const playlist = await youtube.getPlaylist(url)
playlist.videos instanceof PlaylistVideos ? playlist.videos.items : playlist.videos
SuspiciousLookingOwl commented 10 months ago

.getPlaylist() can return a Playlist (which is a normal playlist, with pagination and stuff), and MixPlaylist (which is a playlist YouTube made for individual user, it doesn't have pagination or even dedicated Playlist page).

Here's an example for YouTube Mix playlist

You have to check whether the fetched playlist is a normal Playlist, or a MixPlayist, similar to what you did

const playlist = await youtube.getPlaylist(url);

if (playlist instanceof Playlist) {
  // a normal playlist
  playlist.videos.items;
} else {
  // a mix playlist by YouTube
  playlist.videos;
}

If you are 100% sure that the ID you are trying to fetch is a Playlist and not a MixPlaylist you can pass a generic type


const playlist = await youtube.getPlaylist<Playlist>(url);

playlist.videos.items;
aervxa commented 9 months ago

Aha, I get it!