Nice programing

Typescript에서 키-값 쌍을 사용할 수 있습니까?

nicepro 2020. 11. 29. 12:15
반응형

Typescript에서 키-값 쌍을 사용할 수 있습니까?


키, 값 쌍을 typescript에서 사용할 수 있습니까? 그렇다면 어떻게해야합니다. 누구나 샘플 예제 링크를 제공 할 수 있습니다.


Typescript에서 키-값 쌍을 사용할 수 있습니까?

예. 색인 서명 이라고 합니다 .

interface Foo {
   [key: string]: Bar;
} 
let foo:Foo = {};

여기에 키가 string있고 값은 Bar입니다.

의해 polyfilledMap 적절한 사전에 es6 사용할 수 있습니다 .core-js


가장 간단한 방법은 다음과 같습니다.

var indexedArray: {[key: string]: number}

Typescript에서 키-값 쌍을 사용할 수 있습니까?

C # KeyValuePair <string, string> : 아니요,하지만 직접 쉽게 정의 할 수 있습니다.

interface KeyValuePair {
    key: string;
    value: string;
}

용법:

let foo: KeyValuePair = { key: "k", value: "val" };

질문자 용이 아니라 관심있는 다른 모든 사용자 : 참조 : 키 값 쌍의 Typescript 맵을 정의하는 방법. 여기서 키는 숫자이고 값은 객체의 배열입니다.

따라서 해결책은 다음과 같습니다.

let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;

건배!


키 값 쌍의 예는 다음과 같습니다.

[key: string]: string

값으로 무엇이든 넣을 수 있습니다. 유형이 다른 값을 프로그래밍 방식으로 채운 경우 다음을 넣을 수 있습니다.

[key: string]: any

귀하의 재량에 따라 진행하십시오 any:)


또 다른 간단한 방법은 튜플 을 사용하는 것입니다 .

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);

산출:

첫째 : 안녕하세요 둘째 : 10


class Pair<T1, T2> {
    private key: T1;
    private value: T2;

    constructor(key: T1, value: T2) {
        this.key = key;
        this.value = value;
    }

    getKey() {
        return this.key;
    }

    getValue() {
        return this.value;
    }
}
const myPair = new Pair<string, number>('test', 123);
console.log(myPair.getKey(), myPair.getValue());

Jack miller가 인터페이스를 만들 필요가 없다고 만 말한 것처럼 어떤 방식 으로든 만들 수 있습니다.

let keyValues: any = [
    { key: "2013 Volkswagen Polo 1.4", value: "" },
    { key: "Monthly installment", value: "R2,000.00" },
    { key: "Paid over", value: "72 Months" },
    { key: "Deposit amount", value: "R60,000.00" }
  ];

다음 Record과 같이를 사용할 수도 있습니다 .

const someArray: Record<string, string>[] = [
    {'first': 'one'},
    {'second': 'two'}
];

또는 다음과 같이 작성하십시오.

const someArray: {key: string, value: string}[] = [
    {key: 'first', value: 'one'},
    {key: 'second', value: 'two'}
];

참고 URL : https://stackoverflow.com/questions/36467469/is-key-value-pair-available-in-typescript

반응형