大多数时候对我来说,需要动态检查来验证 fetch 响应。我在想,这可以用用户定义的 typeguard 以通用方式完成,用于具有多个 props 和附加检查的任何类型的对象,因此可以使用以下内容:
// ================= shared exported =================
type Writer = {
name: string
age: number
}
type Book = {
id: number
name: string
tags: string[] | null
writers: Writer[]
}
// function to check object with multiple props general shape, to not do it by hand
function ofType<T>(obj: any): obj is T {
if (!obj) return false;
// how to?
return true // or false
}
// ================= used and defined …Run Code Online (Sandbox Code Playgroud) typescript ×1