简体   繁体   English

如何在 typescript 中为文字名称编写泛型类型?

[英]How to write generic type for literal name in typescript?

I am writing d.ts file for js-data library, and the following code can simplify my demands:我正在为js-data库编写d.ts文件,下面的代码可以简化我的需求:

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

Based on above definitions, I can invoke functions for type checks:基于上述定义,我可以调用函数进行类型检查:

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

Though I can write as many as possible overloading functions like above, but the work is too tedious.虽然我可以写尽可能多的像上面这样的重载函数,但是工作太繁琐了。 Is there any way to simplify such work with generics?有什么方法可以使用 generics 简化此类工作?

type Attrs = {
  note: Note
  comment: Comment
}

type AttrName = keyof Attrs

declare function create<T extends AttrName>(name: T, attrs: Attrs[T]): Note

playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM