0

Updated with missing headerStyles type

Good day everyone. I've been trying to create a dynamic style adding function for table th elements:


type headerStyles = { textAlign: string; backgroundColor?: string };

const exampleData:[string, {
    textAlign: string;
    backgroundColor?: string;
}] = [
['header text1', { textAlign: 'left' }],
['header text2', { textAlign: 'center' }]
['header text3', { textAlign: 'left', backgroundColor: '#ddd' }]
['header text4', { textAlign: 'left' }]
]



const renderHeader = (headers: [string, headerStyles][]) => {
  const head = document.createElement('thead');
  const row = document.createElement('tr');
  headers.forEach(headerProps => {
    const th = document.createElement('th');
    const styles = headerProps[1];

    Object.keys(styles).forEach(prop => {
      th.style[prop] = styles[prop]; // <--- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'headerStyles'
    });
  });
  ...
};

I've tried assigning [prop as keyof typeof styles] from here, however it didn't help since some keys might be undefined (like backgroundColor).

Tried adding if (prop !== undefined) check, which also didn't help.

Tried assigning [key:string] type link, however again, key might be undefined.

Is there any way without adding a bunch of empty 'backgroundColor keys in data object?

1 Answers1

0

Here's one way about it -

type HeaderStyles = {
    textAlign: string;
    backgroundColor?: string;
}

const exampleData: [string, HeaderStyles][] = [
    ['header text1', { textAlign: 'left' }],
    ['header text2', { textAlign: 'center' }],
    ['header text3', { textAlign: 'left', backgroundColor: '#ddd' }],
    ['header text4', { textAlign: 'left' }]
]



const renderHeader = (headers: [string, HeaderStyles][]) => {
    const head = document.createElement('thead');
    const row = document.createElement('tr');
    headers.forEach(headerProps => {
        const th = document.createElement('th');
        const styles = headerProps[1];

        (Object.keys(styles) as Array<keyof HeaderStyles>).forEach(prop => {
            const style = styles[prop];
            if (style) {
                th.style[prop] = style; // <--- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'headerStyles'
            }
        });
    });
};

Here's a playground link.

0xts
  • 2,411
  • 8
  • 16