Why use variable names as keys in object properties instead of variable values?
P粉129168206
2023-08-15 14:11:32
<p>I'm trying to use a <code>Record<TableId, TableState></code> object where <code>type TableId = string;</code>. However, when I print the contents of the record object after setting the key/value pairs via <code>setTableStateMap(map)</code>... what I get is the object <code>{id: {…}} </code> instead of the value I passed to the 'id' variable. </p>
<pre class="brush:php;toolbar:false;">// App.tsx------------------------------ ----------
React.useEffect(() => {
setCallback((id: TableId, tableState: TableState) => {
const map: Record<TableId, TableState> = { id: tableState };
setTableStateMap(map);
});
// Table Component----------------------------------
type TableId = string;
type Callback = (id: TableId, state: TableState) => void;
let callback: Callback;
export function setCallback(callbackInput: Callback) {
callback = callbackInput;
}
let stateMap: Record<TableId, TableState> = {};
export function setTableStateMap(map: Record<TableId, TableState>) {
stateMap = map;
}
interface TableProps {
id?: TableId;
}
export const Table: React.FC<TableProps> = ({
ID,
}) => {
let tableState: TableState | undefined;
if (id) {
tableState = stateMap[id];
// The key of stateMap is set to 'id', not the value of the variable id
// {id: {…}}
} else {
tableState = undefined;
}
};</pre>
<p><br /></p>
When you create an object using curly braces like { id: tableState }, the string "id" is interpreted as a static key instead of the dynamic value of the id variable. You need to use computed property names in JavaScript/TypeScript. Computed property names allow you to use dynamic values as keys when creating objects.