代码之家  ›  专栏  ›  技术社区  ›  Jack Wilsdon HelloWorld

TypeScript根据键映射类型值

  •  0
  • Jack Wilsdon HelloWorld  · 技术社区  · 7 年前

    我可以根据项目的键约束地图条目的值类型吗?

    type Thing<T extends string = any> = {
        type: T
    }
    
    type ThingMap<T extends Thing> = {
        [K in T["type"]]: T
    }
    
    interface A {
        type: "A",
        foo: boolean,
    }
    
    interface B {
        type: "B",
    }
    
    
    // This compiles.
    const map: ThingMap<A | B> = {
        A: { type: "A", foo: true },
        B: { type: "B" },
    }
    
    // But this also compiles, when it should not.
    const map: ThingMap<A | B> = {
        A: { type: "A", foo: true },
        B: { type: "A", foo: true },
    }
    
    0 回复  |  直到 7 年前
        1
  •  3
  •   Titian Cernicova-Dragomir    7 年前

    你想确保某个特定的 K 钥匙的类型不是整个接头(即 T )而是工会的成员 K .你可以用 Extract 得到拥有财产的工会成员 type 类型 K :

    type Thing<T extends string = any> = {
        type: T
    }
    
    type ThingMap<T extends Thing> = {
        [K in T["type"]]:  Extract<T, { type : K }>  // Extract the union member that has { type: K }
    }
    
    interface A {
        type: "A",
        foo: boolean,
    }
    
    interface B {
        type: "B",
    }
    
    
    // This compiles.
    const map: ThingMap<A | B> = {
        A: { type: "A", foo: true },
        B: { type: "B" },
    }
    
    // Err now
    const map2: ThingMap<A | B> = {
        A: { type: "A", foo: true },
        B: { type: "A", foo: true },
    }