打字稿无法确定类型

时间:2019-08-15 11:55:09

标签: typescript

我有2个具有匹配界面的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)

1 个答案:

答案 0 :(得分:0)

#lang racket (define-struct mycons (left right) #:mutable #:transparent) (define (mylist? l) (cond [(empty? l) #t] [(mycons? l) ...] [... ])) (define correct (make-mycons (make-mycons 1 empty) (make-mycons 1 empty))) (define wrong (make-mycons 3 (make-mycons 2 4))) ;;; expect (equal? (mylist? empty) #t) (equal? (mylist? correct) #t) (equal? (mylist? wrong) #f) 接受getCatSize。因此,您可以分配具有Catsize的{​​{1}}属性的对象,但是要分配有关使用number还是string调用函数的信息不会以任何方式捕获版本。此外,函数本身返回number,打字稿不能隐式遵循string上的测试与返回值之间的关系。

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

number | string

Play