【发布时间】:2021-06-27 07:25:14
【问题描述】:
在打字稿中,您可以通过添加使用Omit 删除字段来重新创建类型:
interface Animal {
name: string
}
interface Dog extends Animal {
goodboy: true
}
const makeDog = (name: string, attributes: Omit<Dog, 'name'>): Dog => ({
...attributes,
name
})
但是,当您尝试使用泛型类型执行此操作时,它会失败并出现错误:
// Type 'Omit<T, "name"> & { name: string; }' is not assignable to type 'T'.
// 'Omit<T, "name"> & { name: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Animal'.
const makeAnimal = <T extends Animal>(name: string, attributes: Omit<T, 'name'>): T => ({
...attributes,
name
})
有没有办法创建makeAnimal 函数?
【问题讨论】:
标签: typescript generics types