키와 값의 페어를 타입 스크립트에서 사용할 수 있습니까?
키와 값의 쌍이 타이프 스크립트로 제공됩니까?'네'인 경우 어떻게 해야 합니까?링크의 샘플은 누구나 제공할 수 있습니다.
키와 값의 페어를 타입 스크립트에서 사용할 수 있습니까?
interface Foo {
[key: string]: number;
}
let foo:Foo = {};
foo['hello'] = 123;
foo = {
'leet': 1337
};
console.log(foo['leet']); // 1337
여기 키가 있습니다.string및 값은number.
더
es6를 사용할 수 있습니다.Map적절한 사전의 경우, 에 의해 폴리필됩니다.
가장 간단한 방법은 다음과 같습니다.
var indexedArray: {[key: string]: number}
사용방법:
var indexedArray: {[key: string]: number} = {
foo: 2118,
bar: 2118
}
indexedArray['foo'] = 2118;
indexedArray.foo= 2118;
let foo = indexedArray['myKey'];
let bar = indexedArray.myKey;
또, 다음의 기능을 사용하는 것도 고려해 주세요.Record, 다음과 같이 합니다.
const someArray: Record<string, string>[] = [
{'first': 'one'},
{'second': 'two'}
];
또는 다음과 같이 적습니다.
const someArray: {key: string, value: string}[] = [
{key: 'first', value: 'one'},
{key: 'second', value: 'two'}
];
키와 값의 페어를 타입 스크립트에서 사용할 수 있습니까?
C# Key Value Pair <string, string>을 생각할 경우:아니요, 하지만 스스로 쉽게 정의할 수 있습니다.
interface KeyValuePair {
key: string;
value: string;
}
사용방법:
let foo: KeyValuePair = { key: "k", value: "val" };
또 하나의 간단한 방법은 태플을 사용하는 것입니다.
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);
출력:
첫 번째: 안녕하세요 두 번째: 10
질문자가 아닌 관심 있는 다른 모든 질문자를 대상으로 합니다.자세한 내용은 키 값 쌍의 유형 스크립트 맵을 정의하는 방법을 참조하십시오. 여기서 key는 숫자이고 value는 개체의 배열입니다.
따라서 해결책은 다음과 같습니다.
let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;
건배!
키 값 쌍의 예를 다음에 나타냅니다.
[key: string]: string
물론 어떤 것이든 가치로 삼을 수 있다
간단한 방법은 키와 값의 쌍으로 태플을 사용하는 것입니다.
const keyVal: [string, string] = ["key", "value"] // explicit type
const keyVal2 = ["key", "value"] as const // inferred type with const assertion
const [key, val] = ["key", "val"] // usage with array destructuring
일반을 생성할 수 있습니다.KeyValuePair재사용 가능 유형:
type KeyValuePair<K extends PropertyKey, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]
TS 4.0
에는 라벨이 붙은 태플 요소가 포함되어 있어 문서 작성 및 툴링 지원이 향상됩니다.
type KeyValuePairNamed = [key: string, value: string] // "key" and "value" labels
호환성.
[key, value]tuples는 JS 기본 제공 개체와의 호환성도 보장합니다.
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());
Record를 간단하게 사용할 수도 있습니다.
type Foo = Record<string, number>
문서에서의 추가 사용
TypeScript에는 Map이 있습니다.다음과 같이 사용할 수 있습니다.
public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);
myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data
KeyValue 인터페이스는 형식 스크립트를 사용하는 각도 라이브러리에 있습니다.프로젝트가 각진 경우 이 범용 인터페이스를 사용할 수 있습니다.또는 TS를 angular로 사용하지 않는 경우 선언을 사용하여 최적의 범용 KeyValue 인터페이스를 얻을 수 있습니다.
export declare interface KeyValue<K, V> {
key: K;
value: V;
}
아래 예를 사용하려는 경우
예: { value1: "value1" }
또한 조건에 따라 conditional Data를 동적으로 추가합니다.Try
let dataToWrite: any = {value1: "value1"};
if(conditionalData)
dataToWrite["conditionalData"] = conditionalData
언급URL : https://stackoverflow.com/questions/36467469/is-key-value-pair-available-in-typescript
'programing' 카테고리의 다른 글
| spring boot web-client에서 콘텐츠타입 어플리케이션/x-www-form-urlencoded 폼 데이터 요청을 게시하는 방법 (0) | 2023.03.10 |
|---|---|
| 콘솔에 표시:네트워크 속도가 느리다.로드하는 동안 예비 글꼴이 사용됩니다. (0) | 2023.03.10 |
| 부트스트랩:드롭다운 탐색 부모 링크를 활성화하려면 어떻게 해야 합니까? (0) | 2023.03.05 |
| 중첩된 속성과 함께 개체 범위를 사용하는 방법 (0) | 2023.03.05 |
| ES6 클래스로 스태틱스 대응 (0) | 2023.03.05 |
