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

typescript 中 interface 和泛型描述一个参数的区别

  •  
  •   tuihou123321 · May 18, 2021 · 1299 views
    This topic created in 1808 days ago, the information mentioned may be changed or developed.

    下面有两个函数,mergeObj 函数使用 interface 定义,copyFields 使用泛型定义;使用泛型定义的可以能正常提示出错误,而 mergeObj 不行;如果要使用 interface 实现下面泛型的功能,要如何修改?

    // 泛型,多个类型参数互联约束

    // target 类型要包含 source 的类型

    interface Source { }

    interface Target extends Source { }

    function mergeObj(target:Target, source:Source): Target { for (let key in source){ target[key]=(source)[key]; } return target; }

    let obj={a:1, b:2}; let obj2={c:4};

    console.log(mergeObj(obj, obj2)); // 没有报错提示

    function copyFields<T extends U, U>(target: T, source: U): T { for (let id in source) { target[id] = (<T>source)[id]; } return target; }

    let x = { a: 1, b: 2 };

    copyFields(x, { c: 10 });

    3 replies    2021-05-19 10:24:39 +08:00
    EridanusSora
        1
    EridanusSora  
       May 18, 2021 via Android
    这个就是标准的用泛型的场景呀
    jguo
        2
    jguo  
       May 19, 2021
    你似乎没理解什么是 structural typing,interface Source {}等于啥也没限制
    hive
        3
    hive  
       May 19, 2021
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2455 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 05:15 · PVG 13:15 · LAX 22:15 · JFK 01:15
    ♥ Do have faith in what you're doing.