Typescript无法确定类型

Typescript无法确定类型,typescript,Typescript,我有两个具有匹配接口的cat对象 有人能解释一下为什么我不能将c1设置为数字,c2设置为字符串吗 难道它不能推断函数中的类型吗 interface Cat { name: string; size: string | number; } function getCatSize(cat : Cat) { if ( isNaN(Number(cat.size))) { return cat.size; } else { re

我有两个具有匹配接口的cat对象

有人能解释一下为什么我不能将c1设置为数字,c2设置为字符串吗

难道它不能推断函数中的类型吗

interface Cat {
    name: string;
    size:  string | number;
}

function getCatSize(cat : Cat)  {

    if ( isNaN(Number(cat.size)))  {
        return cat.size;
    } else { 
        return cat.size;
    }
}


  let cat1 : Cat = {
    name: "Cat1",
    size:  "Big"
  };

  let cat2 : Cat = {
    name: "Cat2",
    size:  10
  };


  var c1 : string = getCatSize(cat1);
  // Type 'string | number' is not assignable to type 'string'. 
  // Type 'number' is not assignable to type 'string'

  var c2 : number = getCatSize(cat2);
  // Type 'string | number' is not assignable to type 'number'.
  // Type 'string' is not assignable to type 'number'.ts(2322)


getCatSize
接受
Cat
。因此,您可以使用
size
属性指定一个对象,该属性是
number
string
,但不会以任何方式捕获有关是否使用
number
string
版本调用函数的信息。此外,函数本身返回
number | string
,typescript不能隐式地遵循
size
上的测试与返回值之间的关系

您可以编写一个函数,该函数使用泛型类型参数捕获调用该函数的实际类型并返回该类型

interface Cat<T extends string | number = string | number> {
    name: string;
    size: T;
}
function getCatSize<T extends string | number>(cat: Cat<T>): T {

    if (isNaN(Number(cat.size))) {
        return cat.size;
    } else {
        return cat.size;
    }
}


let cat1: Cat<string> = {
    name: "Cat1",
    size: "Big"
};

let cat2: Cat<number> = {
    name: "Cat2",
    size: 10
};


var c1: string = getCatSize(cat1);

var c2: number = getCatSize(cat2);
接口猫{
名称:字符串;
尺寸:T;
}
功能getCatSize(cat:cat):T{
如果(isNaN(编号(类别尺寸))){
返回猫的大小;
}否则{
返回猫的大小;
}
}
设cat1:Cat={
名称:“Cat1”,
尺寸:“大”
};
设cat2:Cat={
名称:“Cat2”,
尺码:10
};
变量c1:字符串=getCatSize(cat1);
变量c2:编号=getCatSize(cat2);

getCatSize
接受
Cat
。因此,您可以使用
size
属性指定一个对象,该属性是
number
string
,但不会以任何方式捕获有关是否使用
number
string
版本调用函数的信息。此外,函数本身返回
number | string
,typescript不能隐式地遵循
size
上的测试与返回值之间的关系

您可以编写一个函数,该函数使用泛型类型参数捕获调用该函数的实际类型并返回该类型

interface Cat<T extends string | number = string | number> {
    name: string;
    size: T;
}
function getCatSize<T extends string | number>(cat: Cat<T>): T {

    if (isNaN(Number(cat.size))) {
        return cat.size;
    } else {
        return cat.size;
    }
}


let cat1: Cat<string> = {
    name: "Cat1",
    size: "Big"
};

let cat2: Cat<number> = {
    name: "Cat2",
    size: 10
};


var c1: string = getCatSize(cat1);

var c2: number = getCatSize(cat2);
接口猫{
名称:字符串;
尺寸:T;
}
功能getCatSize(cat:cat):T{
如果(isNaN(编号(类别尺寸))){
返回猫的大小;
}否则{
返回猫的大小;
}
}
设cat1:Cat={
名称:“Cat1”,
尺寸:“大”
};
设cat2:Cat={
名称:“Cat2”,
尺码:10
};
变量c1:字符串=getCatSize(cat1);
变量c2:编号=getCatSize(cat2);