V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
mosade

关于 typescript 条件类型中的 extends

  •  
  •   mosade · Jul 20, 2021 · 1624 views
    This topic created in 1752 days ago, the information mentioned may be changed or developed.
    interface Info{
      name:string;
      date:string;
      address:string;
    }
    interface PickInfo{
      address:string;
    }
    
    type Test<T>=T extends PickInfo?string:number;
    type Test2=Test<Info>;
    //==>type Test2 = string
    
    

    Test2 显示的是 string 类型,这里T extends PickInfo不是子集的意思吗?

    2 replies    2021-07-21 10:35:27 +08:00
    noe132
        1
    noe132  
       Jul 20, 2021   ❤️ 1
    T extends Q ? U : V
    的意思是
    let a: T = somevalue
    let b: Q = a
    如果 变量 a 能 赋值给 变量 b 没有类型错误则返回 U 否则 V.

    typescript interface 没有实际类型,是个 ducktype,所以你可以把 (U & V)类型的值赋值给 V 类型的变量
    PickInfo 类型的变量可以接收 Info 类型的值,因为 Info 满足 PickInfo 所有的要求。
    chnwillliu
        2
    chnwillliu  
       Jul 21, 2021 via Android   ❤️ 1
    T extends P, 说明 T 类型 是 P 类型的一种,但是 T 类型可能比 P 类型存在更多的类型描述,即所谓 extends 的含义。Cat extends Animal, 但是 Cat 比 Animal 描述更确切,更具体。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1604 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 16:29 · PVG 00:29 · LAX 09:29 · JFK 12:29
    ♥ Do have faith in what you're doing.