0
입력 개체에 따라 올바른 형식을 반환하는 형식화 된 Promise.props (...) 유틸리티 함수를 만들고 싶습니다.Typescript로 Promise.props (...)에 제네릭 형식 추가
static async props<T extends {[key: string]: Promise<S>|S}, S, U extends { [key in keyof T]: S}>(obj: T): Promise<U> {
const promises = [];
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
promises.push(obj[key]);
}
const results = await Promise.all(promises);
return results.reduce((map, current, index) => {
map[keys[index]] = current;
return map;
}, {});
}
지금까지 입력 매개 변수 인 T
이 있습니다. 또한 같은 키를 가지고 있지만 값 유형이 다른 U
을 정의했습니다.
Promise에서 결과 유형을 가져올 수 있으며 입력 매개 변수의 키를 가져 오는 것과 같은 방법으로 가져올 수 있습니다.
const result = await this.props({
val1: Promise.resolve('test'),
val2: Promise.resolve(123),
val3: ['a', 'b', 'c']
});
IDE는 다음 알아야 : :이 일을해야한다고 생각
result.val1 is a string
result.val2 is a number
result.val3 is an array
다음과 같이 표시한다 기능을 사용
컴파일러를 행복하게 만들기 위해서''obj [key]'''''''obj [key any any]''로 변경하십시오. 그것과는 별도로 작동합니다. –