Home > front end >  How to properly set the type for property `d` in `path` element in a d3 react typescript application
How to properly set the type for property `d` in `path` element in a d3 react typescript application

Time:07-06

I'm trying to draw a triangle using the d3 symbol() method and assigned it to a variable symbolTri.

import { symbol, symbolTriangle } from "d3"
const symbolTri = symbol().size(100).type(symbolTriangle)

export const Component = () => {
    // ...
    return (
        <g>
            <path d={symbolTri()} />
        </g>
    )
}

But while setting the d property a typescript error Type 'string | null' is not assignable to type 'string | undefined'. occurred. And while hovering over the error it shows 'd' value should be of type d?: string | undefined;. But I'm unable to set it properly. Any help, or suggestion would be really helpful.

CodePudding user response:

The easiest solution, assuming that the output of symbolTri() cannot be null (which seems a reasonable assumption in this case), is to use the non-null assertion operator, which effectively tells the TypeScript compiler that this variable will never be null:

<path d={symbolTri()!} />
  • Related