분류React 아래의 글

react17, typescript에서
export interface LinesData{
lineId: string;
lineName: string;
cudsKey: string;
_checked: boolean;
}
정의하고

selectLineData: LinesData = []; 했는데

Type 'never[]' is missing 오류 해결해 주세요

에러 메시지 Type 'never[]' is not assignable to type 'LinesData'는 selectLineData를 배열로 초기화했는데, 타입을 단일 객체(LinesData)로 선언했기 때문입니다.

당신의 코드:

ts
복사
편집
export interface LinesData {
lineId: string;
lineName: string;
cudsKey: string;
_checked: boolean;
}

selectLineData: LinesData = []; // ❌ 오류 발생
이건 LinesData 타입에 배열을 대입했기 때문에 타입 불일치로 에러가 발생합니다.

✅ 해결 방법: 타입을 배열로 선언
selectLineData가 여러 개의 라인을 저장하는 배열이라면 다음과 같이 타입을 수정해야 합니다:

ts
복사
편집
selectLineData: LinesData[] = []; // ✅ 배열 타입으로 선언
참고: 단일 객체일 경우
만약 selectLineData가 단일 LinesData 객체라면, 빈 배열이 아니라 객체로 초기화해야 합니다:

ts
복사
편집
selectLineData: LinesData = {
lineId: '',
lineName: '',
cudsKey: '',
_checked: false
};

React, Typescript의 클래스 컴퍼넌트 환경에서 monitoringType 변수가 T 일 경우 'Activity Name'를 리턴하고 S 일 경우
'Monitoring Name'를 리턴하는 예제 만들어 주세요.

import React, { Component } from 'react';

type MonitoringType = 'T' | 'S';

interface Props {
monitoringType: MonitoringType;
}

class MonitoringLabel extends Component {
getLabel = (): string => {

const { monitoringType } = this.props;

switch (monitoringType) {
  case 'T':
    return 'Activity Name';
  case 'S':
    return 'Monitoring Name';
  default:
    return 'Unknown';
}

};

render() {

return (
  <div>
    <label>{this.getLabel()}</label>
  </div>
);

}
}

export default MonitoringLabel;

switch 문장 말고 간단하게 T이면 Activity Name 나머지는 Monitoring Name 으로 간략하게 수정해주세요

import React, { Component } from 'react';

type MonitoringType = 'T' | 'S';

interface Props {
monitoringType: MonitoringType;
}

class MonitoringLabel extends Component {
getLabel = (): string => {

return this.props.monitoringType === 'T' ? 'Activity Name' : 'Monitoring Name';

};

render() {

return (
  <div>
    <label>{this.getLabel()}</label>
  </div>
);

}
}

export default MonitoringLabel;

monitorStore.ts

import { makeAutoObservable } from "mobx";

export type MonitoringCycle = 'DAILY' | 'WEEKLY' | 'MONTHLY';

export class MonitorStore {
cycle: MonitoringCycle = 'DAILY';
startTime: string = '';
dayOfWeek: string = 'MON';
dayOfMonth: number = 1;

constructor() {

makeAutoObservable(this);

}

setCycle = (cycle: MonitoringCycle) => {

this.cycle = cycle;

};

setStartTime = (time: string) => {

this.startTime = time;

};

setDayOfWeek = (day: string) => {

this.dayOfWeek = day;

};

setDayOfMonth = (day: number) => {

this.dayOfMonth = day;

};
}

export const monitorStore = new MonitorStore();
Monitor.tsx
tsx
복사
편집
import React from 'react';
import { observer } from 'mobx-react-lite';
import { monitorStore } from './monitorStore';

export const Monitor = observer(() => {
const store = monitorStore;

const handleCycleChange = (e: React.ChangeEvent) => {

store.setCycle(e.target.value as any);

};

const handleStartTimeChange = (e: React.ChangeEvent) => {

store.setStartTime(e.target.value);

};

const handleDayOfWeekChange = (e: React.ChangeEvent) => {

store.setDayOfWeek(e.target.value);

};

const handleDayOfMonthChange = (e: React.ChangeEvent) => {

store.setDayOfMonth(Number(e.target.value));

};

const renderDayOfWeekOptions = () => {

const days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];
return (
  <div>
    <label>요일 선택: </label>
    {days.map(day => (
      <label key={day} style={{ marginRight: 10 }}>
        <input
          type="radio"
          name="dayOfWeek"
          value={day}
          checked={store.dayOfWeek === day}
          onChange={handleDayOfWeekChange}
        />
        {day}
      </label>
    ))}
  </div>
);

};

const renderDayOfMonthOptions = () => {

return (
  <div>
    <label>날짜 선택: </label>
    <select value={store.dayOfMonth} onChange={handleDayOfMonthChange}>
      {Array.from({ length: 31 }, (_, i) => i + 1).map(day => (
        <option key={day} value={day}>
          {day}일
        </option>
      ))}
    </select>
  </div>
);

};

return (

<div style={{ padding: 20, fontFamily: 'Arial' }}>
  <h3>모니터링 주기 설정</h3>

  <div style={{ marginBottom: 10 }}>
    <label>주기 선택: </label>
    {(['DAILY', 'WEEKLY', 'MONTHLY'] as const).map((type) => (
      <label key={type} style={{ marginRight: 10 }}>
        <input
          type="radio"
          name="cycle"
          value={type}
          checked={store.cycle === type}
          onChange={handleCycleChange}
        />
        {type}
      </label>
    ))}
  </div>

  <div style={{ marginBottom: 10 }}>
    <label>Start Time: </label>
    <input
      type="text"
      value={store.startTime}
      onChange={handleStartTimeChange}
      placeholder="HH:mm"
    />
  </div>

  {store.cycle === 'WEEKLY' && renderDayOfWeekOptions()}
  {store.cycle === 'MONTHLY' && renderDayOfMonthOptions()}
</div>

);
});
index.tsx
tsx
복사
편집
import React from 'react';
import ReactDOM from 'react-dom';
import { Monitor } from './Monitor';

ReactDOM.render(
<React.StrictMode>

<Monitor />

</React.StrictMode>,
document.getElementById('root')
);

import React, { Component } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { ColDef } from 'ag-grid-community';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

interface RowData {
id: number;
name: string;
chkResult: 'N' | 'W' | 'E';
}

interface State {
columnDefs: ColDef[];
rowData: RowData[];
}

export class SignalGrid extends Component<{}, State> {
constructor(props: {}) {

super(props);

this.state = {
  columnDefs: [
    { field: 'id', headerName: 'ID', width: 80 },
    { field: 'name', headerName: 'Name', width: 150 },
    {
      field: 'chkResult',
      headerName: 'Result',
      cellRenderer: this.signalRenderer,
      width: 150,
    },
  ],
  rowData: [
    { id: 1, name: 'Item A', chkResult: 'N' },
    { id: 2, name: 'Item B', chkResult: 'W' },
    { id: 3, name: 'Item C', chkResult: 'E' },
  ],
};

}

// 셀 렌더러 함수
signalRenderer(params: any) {

const value = params.value;
let color = 'gray';

if (value === 'W') color = 'gold';
else if (value === 'E') color = 'red';

return (
  `<span style="display: flex; align-items: center;">
    <span style="
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background-color: ${color};
      margin-right: 6px;
    "></span>
    ${value}
  </span>`
);

}

render() {

return (
  <div
    className="ag-theme-alpine"
    style={{ height: 300, width: 400 }}
  >
    <AgGridReact
      columnDefs={this.state.columnDefs}
      rowData={this.state.rowData}
    />
  </div>
);

}
}

import React, { Component } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { ColDef } from 'ag-grid-community';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const processTypeMap: Record<string, string> = {
PROCESS: 'Process',
VERIFY: 'Answer',
NOTFIY: 'Notify', // 'NOTIFY' 오타 여부 확인 필요
};

interface RowData {
id: number;
processType: string;
}

interface State {
columnDefs: ColDef[];
rowData: RowData[];
}

export class ProcessGrid extends Component<{}, State> {
constructor(props: {}) {

super(props);
this.state = {
  columnDefs: [
    { headerName: 'ID', field: 'id' },
    {
      headerName: '처리 유형',
      field: 'processType',
      valueFormatter: (params) => processTypeMap[params.value] || params.value,
    },
  ],
  rowData: [
    { id: 1, processType: 'PROCESS' },
    { id: 2, processType: 'VERIFY' },
    { id: 3, processType: 'NOTFIY' },
  ],
};

}

render() {

return (
  <div className="ag-theme-alpine" style={{ height: 300, width: '100%' }}>
    <AgGridReact
      columnDefs={this.state.columnDefs}
      rowData={this.state.rowData}
    />
  </div>
);

}
}