我正在d.ts為js-data庫撰寫檔案,以下代碼可以簡化我的需求:
interface Note {
id: number,
title: string,
text: string
}
interface Comment {
id: number,
content: string,
noteId: number
}
function create(name: 'note', attrs: Note): Note
function create(name: 'comment', attrs: Comment): Comment
// ... and so on
基于上述定義,我可以呼叫函式進行型別檢查:
create('note', { id: 1, title: 'note title', body: 'note body' }) // work
create('comment', { id: 11, content: 'comment content', noteId: 1 }) // work
create('nott', ...) // not work, there is a spelling mistake
create('note', { id: 11, content: 'comment content', noteId: 1 }) // not work, attrs should be type Note
雖然我可以寫盡可能多的像上面這樣的多載函式,但是作業太繁瑣了。有沒有辦法用泛型來簡化這樣的作業?
uj5u.com熱心網友回復:
type Attrs = {
note: Note
comment: Comment
}
type AttrName = keyof Attrs
declare function create<T extends AttrName>(name: T, attrs: Attrs[T]): Note
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364919.html
上一篇:我該如何解決androidx.appcompat.widget.SearchView無法強制轉換為android.widget.SearchView
下一篇:視圖函式沒有在前面渲染資料
