我想用泛型验证返回类型。但是像打击这样的行为让我很困惑:
public function generate()
{
为什么当返回类型扩展为泛型类型时,它可以通过类型检查?
答案 0 :(得分:1)
不知为何 { name: '123', error: '123' } 也能通过类型检查。error 未定义
这是因为可分配性。
请考虑下一个例子:
interface IT {
name: string;
}
interface check<T> {
get(): Partial<T>;
};
var g: check<IT> = {
get() {
return {
name: 'sdsdf',
error: 'asdad'
}
}
}
interface IT2 {
name: string,
error: string
}
declare var a: IT
declare var b: IT2
a = b // ok
b = a // error
如您所见,IT2 可以分配给 IT,但反之则不然。
但是为什么???
这就是类型在 TypeScript 中的工作方式。请参阅 docs
的第一个示例 <块引用>类型检查器检查对 printLabel 的调用。 printLabel 函数有一个参数,该参数要求传入的对象具有一个称为字符串类型的标签属性。请注意,我们的对象实际上具有比这更多的属性,但编译器只检查至少所需的属性是否存在并匹配所需的类型。在某些情况下,TypeScript 不够宽松,我们稍后会介绍。
TypeScript 中没有 Exact
类型,但是有一个开放的 enter link description here
请记住,接下来的代码将失败:
const bar = g.get().error // error
答案 1 :(得分:0)
因为您在返回中使用的类型与您在接口中定义的类型不同。
interface IT {
name: string;
}
// this will work
var e: check<IT> = {
get() {
return {
name: "123" // needs to be a string
}
}
}
// this will not work
var f: check<IT> = {
get() {
return {
error: 'asdad' // "error" was not a field defined on your interface
}
}
}