@Andy_Francev
Frontend Developer

Как правильно вывести тип возвращаемого значения?

Добрый день! А есть ли способ заставить Typescript выводить тип результата?

interface State1 {
  st: number;
}
interface State2 {
  tmp1: number;
  tmp2: string;
}

const state1: State1 = { st: 1 };
const state2: State2 = { tmp1: 2, tmp2: "3" };

const state = { state1, state2 };

type StateKeys = keyof typeof state;

function getCurrentState(key: StateKeys) {
  return state[key];
}

const currentState = getCurrentState("state1");
  • Вопрос задан
  • 28 просмотров
Пригласить эксперта
Ответы на вопрос 1
meinefinsternis
@meinefinsternis
interface State1 {
  st: number;
}
interface State2 {
  tmp1: number;
  tmp2: string;
}

const state1: State1 = { st: 1 };
const state2: State2 = { tmp1: 2, tmp2: "3" };

const state = { state1, state2 };

function getCurrentState<T extends keyof typeof state>(key: T) {
  return state[key];
}

// const currentState1: State1
const currentState1 = getCurrentState("state1");

// const currentState2: State2
const currentState2 = getCurrentState("state2");
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы