programing

C#과 같이 사전 유형으로 TypeScript 개체

css3 2023. 3. 1. 11:23

C#과 같이 사전 유형으로 TypeScript 개체

개체를 사전으로 사용하는 JavaScript 코드가 있습니다. 예를 들어, '사람' 개체는 이메일 주소에서 제외된 개인 정보를 보관합니다.

var people = {<email> : <'some personal data'>};

adding   > "people[<email>] = <data>;" 
getting  > "var data = people[<email>];" 
deleting > "delete people[<email>];"

이것을 타이프스크립트에 기술할 수 있습니까?아니면 어레이를 사용해야 합니까?

새로운 버전의 typscript에서는 다음을 사용할 수 있습니다.

type Customers = Record<string, Customer>

이전 버전에서는 다음을 사용할 수 있습니다.

var map: { [email: string]: Customer; } = { };
map['foo@gmail.com'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['bar@hotmail.com'] = 'x'; // Not OK, 'x' is not a customer

매번 해당 유형의 주석을 입력하지 않으려는 경우에도 인터페이스를 만들 수 있습니다.

interface StringToCustomerMap {
    [email: string]: Customer;
}

var map: StringToCustomerMap = { };
// Equivalent to first line of above

맵과 같은 오브젝트를 사용하는 것 외에 실제 오브젝트가 한동안 존재해 왔습니다.이 오브젝트는 ES6로 컴파일 할 때나 ES6 타입 정의의 폴리필을 사용할 때 TypeScript에서 사용할 수 있습니다.

let people = new Map<string, Person>();

같은 기능을 서포트합니다.Object및 기타 구문이 약간 다른 경우:

// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });

// Checking for the presence of a key:
people.has("John"); // true

// Retrieving a value by a key:
people.get("John").lastName; // "Doe"

// Deleting an item by a key:
people.delete("John");

이것만 해도 맵과 같은 오브젝트를 사용하는 것에 비해 다음과 같은 몇 가지 이점이 있습니다.

  • 비문자열 기반 키(예: 숫자 또는 객체) 지원(둘 다 지원되지 않음)Object(아니오,Object는 숫자를 지원하지 않습니다.숫자를 문자열로 변환합니다).
  • 사용하지 않을 때 오류가 발생할 여지가 적다--noImplicitAny,로서Map항상 키 유형과 유형이 있는 반면 개체에는 인덱스 유형이 없는 경우가 있습니다.
  • 항목 추가/삭제 기능(키-값 쌍)은 다음에서 속성을 생성하는 것과 달리 태스크에 최적화되어 있습니다.

또,Map오브젝트는 일반적인 태스크에 대해 보다 강력하고 우아한 API를 제공합니다.대부분의 작업은 단순한 작업으로는 이용할 수 없습니다.Object를 해킹하지 않고 도우미 기능을 사용할 수 있습니다(단, 이들 중 일부는 ES5 타깃 또는 그 이하의 완전한 ES6 반복기/반복 가능한 폴리필이 필요합니다).

// Iterate over Map entries:
people.forEach((person, key) => ...);

// Clear the Map:
people.clear();

// Get Map size:
people.size;

// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());

// Extract values into array (in insertion order):
let values = Array.from(people.values());

다음과 같이 템플릿인터페이스를 사용할 수 있습니다.

interface Map<T> {
    [K: string]: T;
}

let dict: Map<number> = {};
dict["one"] = 1;

사용할 수 있습니다.Record이 경우:

https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

예(약속 상태 열거와 일부 메타 데이터 간의 매핑):

  const iconMapping: Record<AppointmentStatus, Icon> = {
    [AppointmentStatus.Failed]: { Name: 'calendar times', Color: 'red' },
    [AppointmentStatus.Canceled]: { Name: 'calendar times outline', Color: 'red' },
    [AppointmentStatus.Confirmed]: { Name: 'calendar check outline', Color: 'green' },
    [AppointmentStatus.Requested]: { Name: 'calendar alternate outline', Color: 'orange' },
    [AppointmentStatus.None]: { Name: 'calendar outline', Color: 'blue' }
  }

interface를 값으로 지정:

interface Icon { Name: string Color: string }

사용방법:

const icon: SemanticIcon = iconMapping[appointment.Status]

typescript에 Record type을 사용할 수도 있습니다.

export interface nameInterface { 
    propName : Record<string, otherComplexInterface> 
}

Lodash는 간단한 사전 구현과 우수한 TypeScript 지원을 제공합니다.

Lodash 설치:

npm install lodash @types/lodash --save

Import 및 사용:

import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
    "key": "value"        
}
console.log(properties["key"])

언급URL : https://stackoverflow.com/questions/13631557/typescript-objects-as-dictionary-types-as-in-c-sharp