Элемент неявно имеет тип any, поскольку выражение типа string не может использоваться для индексации типа A - PullRequest
1 голос
/ 08 июля 2020

Тип A в вопросе относится к этому примеру * Тип 1002 *, а полная ошибка -

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type A.No index signature with a parameter of type 'string' was found on type A

Ссылка на песочницу: https://codesandbox.io/s/typescript-type-checking-question-hkfmc (ПРИМЕЧАНИЕ: Но для по какой-то причине он не показывал ошибку -_-)

У меня проблема, сделайте правильный выбор. и все подобные посты крутятся у меня над головой. Буду признателен за ответ с пояснениями

type BadgeTypes = {
  success: string;
  secondary: string;
  alert: string;
  text: string;
};

type Theme = {
  fonts?: object;
  borderRadius?: string;
  primary?: object;
  accent?: object;
  action?: object;
  stories?: object;
  checkbox?: object;
  badge: BadgeTypes;
  button?: object;
  page?: object;
  states?: object;
  modal?: object;
};
interface Props {
  theme: Theme;
  large: boolean;
  type: keyof BadgeTypes;
}
const StyledBadge = styled.span<Props>`
  display: inline-block;
  border-radius: ${(props: Props) => props.theme.borderRadius};
  text-align: center;
  color: ${(props: Props) => props.theme.badge.text};
  font-size: ${(props: Props) => (props.large ? `1.4rem` : `1rem`)};
  padding: ${(props: Props) =>
    props.large ? `0 .8rem` : `0.2rem 0.6rem 0.3rem 0.6rem`};

  // error happens here
  background: ${(props: Props) => props.theme.badge[`${props.type}`]};
`;

1 Ответ

2 голосов
/ 08 июля 2020

Проблема заключается в использовании строки шаблона для индексации badge.

Обычно:

// this is a string
let x = `${props.type}`;

// this is "success" | "secondary" | "alert" | "text"
let y = props.type;

Если вы пишете props.theme.badge[props.type], проверка типа должна быть счастлив.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...