Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location.

https://i.sstatic.net/5hF2q.png

For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be associated with 000 - TTT PARAMETER.

I hope you understand what I mean.

How do I establish these mappings?

Updated:

I am attempting to achieve this using TypeScript:

export enum IName {
  SmokeSensor = 'SmokeSensor',
  GasSensor = 'GasSensor',
  MotionSensor = 'MotionSensor',
  WindowSensor = 'WindowSensor',
  Sensor = 'Sensor',
  PushButton = 'PushButton',
  Switch = 'Switch',
  Temperature = 'Temperature',
}

export enum ISymbol {
  SS = 'SS',
  SG = 'SG',
  SM = 'SM',
  SW = 'SW',
  SE = 'SE',
  PI = 'PI',
  SI = 'SI',
  TI = 'TI',
}

export enum IParameter {
  TTT = 'TTT',
  OOO = '000',
  OFF = 'OFF',
  OON = 'OON',
  POS = '0',
  NEG = '1',
}

interface IActivateSensors {
  name: Omit<IName, 'Switch' & 'Temperature'>
  symbol: Omit<ISymbol, 'SI' & 'TI'>
  parameter: Pick<IParameter, 'TTT' & '000'>
}

interface ISwitchSensor {
  name: IName.Switch
  symbol: ISymbol.SI
  parameter: Pick<IParameter, 'OFF' & 'OON'>
}

interface ITemperatureSensor {
  name: IName.Temperature
  symbol: Omit<ISymbol, 'SI' & 'TI'>
  parameter: Pick<IParameter, 'TTT' & '000'>
}

export type Sensors = IActivateSensors | ITemperatureSensor | ISwitchSensor

However, there may be a more efficient way to accomplish this.

Answer №1

If you grasp the concept, you can implement it in the following way:

export enum Name {
    SmokeSensor = 'SS',
    GasSensor = 'SG',
    MotionSensor = 'SM',
    WindowSensor = 'SW',
    Sensor = 'SE',
    PushSensor = 'PI',
    Switch = 'SI'
}

export interface Symbol {
    [Name.SmokeSensor]: ParameterRange;
    [Name.GasSensor]: ParameterRange;
    [Name.MotionSensor]: ParameterRange;
    [Name.WindowSensor]: ParameterRange;
    [Name.Sensor]: ParameterRange;
    [Name.PushSensor]: ParameterRange;
    [Name.Switch]: ParameterOnOff;
}

export type ParameterRange = '000' | 'TTT'; // and more
export type ParameterOnOff = 'OFF' | 'OON';

function doStuff<N extends Name>(name: N, parameter: Symbol[N]) {
    // actions
}

However, mapping all values for 000 - TTT is required as they likely represent a range of values.


Edit 1

A potential solution could involve creating constants:

const ParameterRange = {
    '000': '000',
    'TTT': 'TTT'
    // additional values
}

const ParameterOnOff = {
    'OFF': 'OFF',
    'OON': 'OON'
}

export const Values = {
    SmokeSensor: { Symbol: { SS: 'SS' }, Parameter: ParameterRange },
    GasSensor: { Symbol: { SG: 'SG' }, Parameter: ParameterRange },
    MotionSensor: { Symbol: { SM: 'SM' }, Parameter: ParameterRange },
    WindowSensor: { Symbol: { SW: 'SW' }, Parameter: ParameterRange },
    Sensor: { Symbol: { SE: 'SE' }, Parameter: ParameterRange },
    PushSensor: { Symbol: { PI: 'PI' }, Parameter: ParameterRange },
    Switch: { Symbol: { SI: 'SI' }, Parameter: ParameterOnOff }
}

Values.SmokeSensor.Symbol.SS;
Values.Switch.Parameter.OFF;

This approach enforces mapping every value within ParameterRange, eliminating the need for value checks.


Edit 2

Can this be achieved using your enum like so?

type TActivateSensors = { [Name in Exclude<IName, IName.Switch | IName.Temperature>]: { Symbol: Exclude<ISymbol, ISymbol.SI | ISymbol.TI>; Parameter: Extract<IParameter, IParameter.TTT | IParameter.OOO>; } }
type TSwitchSensor = { [Name in Extract<IName, IName.Switch>]: { Symbol: Extract<ISymbol, ISymbol.SI>; Parameter: Extract<IParameter, IParameter.OFF | IParameter.OON>; } }
type TSensors = TActivateSensors & TSwitchSensor;

export type Sensor<Name extends keyof TSensors> = {
    name: Name;
    symbol: TSensors[Name]['Symbol'];
    parameter: TSensors[Name]['Parameter'];
};

const sensor: Sensor<IName.Switch> = {
    name: IName.Switch,
    symbol: ISymbol.SI,
    parameter: IParameter.OFF
}

By utilizing type Sensor on an object, TypeScript mandates the use of allowed enums for each property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

Is it possible to extract elements from a single list and insert them onto various pages?

Currently, I am retrieving items from a list using an ajax call. After constructing the HTML content, I insert these items onto a page. Now, I want to extract the same items and display them on another page with a different style. Is there a method to conn ...

Sorting JSON data using JQuery Ajax

I've encountered an issue with sorting JSON data. Here is the JSON data I'm working with: [ { nom: "TERRES LATINES", numero: "0473343687", image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12 ...

The font size varies depending on the language being used

On a single web page, there are 3 different language words displayed: Language / 한국어 / ภาษาไทย I am interested in enlarging the Thai word (ภาษาไทย) to make it stand out. <span class="thai">ภาษาไท ...

Is it possible to utilize the existing class elements as an array identifier?

Can you leverage a string from an element's CSS class as an array name? I am searching for a more efficient way to store default animations that may expand gradually to encompass more options in the array. Example JavaScript (jQuery): - var col ...

Assigning event to the body element

Is there a way to bind an event to the entire page, specifically the html or body tag? I am trying to achieve the following: document.addEventListener('mousemove', function() { alert('a'); }); I want an alert to be triggered whenever ...

Display the dropdown selected value within a Laravel Blade template

I am facing an issue with passing the selected value from a drop-down to another Blade file in Laravel. I have tried using Ajax and jQuery, but it doesn't seem to work for me. I want to display the selected value on the content.blade.php page without ...

What is the process for inputting data into a Inertia component?

I have a simple component: <script setup> import {ref} from 'vue' const labels = [] </script> <template> <div v-for="(label, index) in labels" :key="index" v-html="label"></div> </t ...

How to Properly Initialize a Variable for Future Use in a Component?

After initializing my component, certain variables remain unassigned until a later point. I am seeking a way to utilize these variables beyond the initialization process, but I am unsure of how to do so. Below is my attempted code snippet, which throws a ...

Calculating date discrepancies with JavaScript

Two fields are present, one for the start date and one for the end date. I would like to display the date difference in another text box when the user selects dates from a date picker. Although I have made some progress on this, I believe that there are st ...

WebStorm disregards tsconfig compiler directives when working with Angular applications

My project structure was created using angular-cli, which includes a root tsconfig.json, src/tsconfig.app.json, and src/tsconfig.spec.json. Despite having the noImplicitAny and strict options enabled in the root configuration, I do not receive error notifi ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Utilizing the String Enum for mapping an interface with an index

Using Typescript, I aim to make use of my string enumeration: export const enum MutationKeys { registerUser = 'registration/REGISTER', registerUserCompleted = 'registration/REGISTER_COMPLETED' } This allows the string values t ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

Issue with a hidden div, problem with scrolling, a div overlapping other divs

I'm feeling a bit lost here, trying to figure out what went wrong. It seems like a simple mistake, but I can't pinpoint it. Currently, I'm just testing everything out for a mobile website template. Hopefully, that information helps. For any ...