Home > Enterprise >  How do I tell typescript to use string as key of a intersection type?
How do I tell typescript to use string as key of a intersection type?

Time:07-23

Initially my code was :

type Point = {
    x: number, y: number
};

type Point3D = Point & {
    z: number
}
function printPoint(p: Point | Point3D) {
    log("Point {");
    for (const coordinate in p) {
        log("\t", p[coordinate])
    }
    log("}")
}
printPoint({ x: 1, y: 2, z: 3 })
printPoint({ x: 0.4, y: 4 })

which would cause the error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type .. to which I found the solution here: https://stackoverflow.com/a/69198602/6591533.

There they suggest to use as keyof Type after your index to get rid of the error :

// This works
for (const coordinate in p) {
        log("\t", p[coordinate as keyof Point])
   }
// This does not
for (const coordinate in p) {
        log("\t", p[coordinate as keyof Point3D])
    }
// Neither this
for (const coordinate in p) {
        log("\t", p[coordinate as keyof Point | Point3D])
    }

CodePudding user response:

Use generics and let typescript infer your parameter's type.

type Point = {
    x: number, y: number
};

type Point3D = Point & {
    z: number
}
function printPoint<T>(p: T) {
    console.log("Point {");
    
    for (const coordinate in p) {
        console.log("\t", p[coordinate])
    }

    console.log("}")
}

printPoint({ x: 1, y: 2, z: 3 })
printPoint({ x: 0.4, y: 4 })

Check this here

Update: you can narrow your type like -

function printPoint<T extends Point | Point3D>(p: T) {}
  • Related