1

Существует 2 готовых типа:

type ContainerData = string;
type ContainerDataArray = string[];

Необходимо написать интерфейс, который имеет одно обязательное поле rootContainer типа ContainerDataArray и неограниченное количество полей с любым названием типа ContainerData. Использование выглядит так:

interface IContainerBundle {
    // Обязательное поле
    rootContainer: ContainerDataArray,

    // Другие поля с любым названием.
    // Есть ли способ реализовать такой функционал?
    // (что-то): ContainerData
}

const containerBundle: IContainerBundle = {
    rootContainer: ["", ""],
    container1: "",
    container2: "",
    // ...
}

Жёсткая привязка к первым двум типам обязательна: так как приложение всё ещё находится на этапе разработки, содержимое типов может изменяться.

Решение вида:

interface IContainerBundle {
    [key: string]: ContainerData | ContainerDataArray
}

не является правильным, так как обязательное поле rootContainer всегда должно быть массивом строк, а остальные поля всегда обычными строками.

Данный функционал используется при инициализации useState в React. Получается что-то типа:

interface IContainerBundle {
    // ...
}
const [container, setContainer] = useState<IContainerBundle>({
    rootContainer: ["...", "..."],
    container1: "",
    container2: ""
    // ...
});

1 ответ 1

0

Playground

type First = { x: number, y: string }
type Second = { id: number, y: number }

type Smth = {
    root: First
} & {
    [key in string]: Second
}

declare var x: Smth

x.root.id // Property 'id' does not exist on type 'First'.
x.root.x = 0
x.root.y = "zzz"

x.other.id = 1
x.other.x // Property 'x' does not exist on type 'Second'.
x.other.y = 2

Немного манипуляций с кастомными хуками: playground

type AreSame<T, U, Y, N> = (<X>() => X extends T ? 1 : 2) extends (<X>() => X extends U ? 1 : 2) ? Y : N;

type First = { x: number, y: string }
type Second = { id: number, y: number }

type Smth<K extends string> = {
    root: First
} & {
    [key in K]: AreSame<key, "root", First, Second>
}

function useSmth<K extends string>(x: Smth<K>) {
    // x.root.id // Property 'id' does not exist on type 'First'.
    x.root.x = 0
    x.root.y = "zzz"

    // Property 'other' does not exist on type 'Smth<K>'.
    // x.other.id = 1
    // x.other.x
    // x.other.y = 2
}

useSmth({
    root: { x: 0, y: "" },
})

useSmth({
    root: { x: 0, y: "" },
    other: { id: 1, y: 2 },
})

function useSmth2<K extends string>(x: Smth<K>): void;
function useSmth2<K extends string>(x: Smth<string>) {
    // x.root.id // Property 'id' does not exist on type 'First'.
    x.root.x = 0
    x.root.y = "zzz"

    x.other.id = 1
    // x.other.x // Property 'x' does not exist on type 'Second'.
    x.other.y = 2
}

useSmth2({
    root: { x: 0, y: "" },
})

useSmth2({
    root: { x: 0, y: "" },
    other: { id: 1, y: 2 },
})
12
  • Есть способ сделать так же, но с инициализацией переменной через const?
    – Vladislav
    8 янв 2022 в 13:32
  • @Vladislav, при чём тут вообще переменная, ты же тип просил - вот он.
    – Qwertiy
    8 янв 2022 в 13:45
  • @Vladislav, а понял. Блин.. Неожиданно. Сейчас подумаю.
    – Qwertiy
    8 янв 2022 в 13:46
  • Тут просто проблема в том, что этот тип используется при инициализации useState в React. const [containers, setContainers] = useState<IContainerBundle>({...}). Поэтому через declare тут не получится сделать :/ Наверное, стоило указать это в вопросе. Прошу прощения.
    – Vladislav
    8 янв 2022 в 13:48
  • @Vladislav, пока ничего лучше каста объекта к нужному типу не придумал. А ты собираешься объект прям в useState запихивать, без функции? Не useState((): IContainerBundle => ({ ... }))?
    – Qwertiy
    8 янв 2022 в 13:51

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.