V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
nulIptr
V2EX  ›  TypeScript

typescript 类型求助

  •  
  •   nulIptr · 2022-04-27 12:17:30 +08:00 · 1518 次点击
    这是一个创建于 701 天前的主题,其中的信息可能已经有所发展或是发生改变。
    二手前端写 react 组件的时候遇到的问题
    先贴代码



    useTableWithCustomKey 的第二个参数 keyName 的类型应该是 T 中所有类型是 string 类型的字段名称。
    然后用 useTableForName 这种形式调用是没问题的
    但是用 useTable 这种再套一个 T extends { name: string },然后传入 name 就不行了,报错是
    Argument of type 'string' is not assignable to parameter of type 'keyof StringOnly<T>'.
    Type '"name"' is not assignable to type '(T[K] extends string ? K : never) | (T["name"] extends string ? "name" : never)'.ts(2345)


    请问怎样才能消除这个报错。
    原始需求是写一个 table 组件,有的对象是用 name 做 key ,有的是用 id 做 key
    再贴一个
    https://codesandbox.io/s/ts-playground-forked-qgnqhg?file=/src/index.ts
    方便大佬们在线测试
    4 条回复    2022-04-27 15:20:56 +08:00
    gydi
        1
    gydi  
       2022-04-27 13:04:50 +08:00
    我改成这样就可以了

    function useTableWithCustomKey<T, K = keyof StringOnly<T>>(
    records: T[],
    keyName: K,
    ) {}
    noe132
        2
    noe132  
       2022-04-27 13:06:56 +08:00
    研究了半天,我找到一个可能是答案的答案
    typescript 目前不支持 partial type parameter inference
    https://stackoverflow.com/questions/64376774/in-typescript-how-can-i-infer-my-arguments-and-impose-a-constraint-that-all-ite

    function useTable<T extends { name: string }>(records: Array<T>) {
    type IsNameInKeys = 'name' extends keyof T ? true : false

    const a: IsNameInKeys = true;
    const b: IsNameInKeys = false;

    return useTableWithCustomKey(records, 'name');
    }
    这个地方 是不是看起来 IsNameInKeys 不是 true 就是 false ?然而 变量 a 和 b 的类型检查都无法通过。
    noe132
        3
    noe132  
       2022-04-27 13:08:25 +08:00
    所以要么所有类型都是具体类型,要么所有类型都是类型参数。1 楼这个例子就是把 keyName 提升到了类型参数
    nulIptr
        4
    nulIptr  
    OP
       2022-04-27 15:20:56 +08:00
    @gydi 这种形式相当于完全没限制 k 的类型呀,函数体里面也不能直接用 records[keyName]了,如果改成下面这样有和我贴出的代码一致了
    function useTableWithCustomKey<T, K extends keyof StringOnly<T>>(
    records: T[],
    keyName: K,
    ) {}



    @noe132 所以看起来就是目前还不能解决这个问题是吧。感觉很奇怪。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4467 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:09 · PVG 18:09 · LAX 03:09 · JFK 06:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.