interface DefaultProps4 {
instantPopoup?: boolean;
// ...
}
interface PropsWithCb4 extends DefaultProps4 {
cb(): void;
}
interface PropsWithPath4 extends DefaultProps4 {
path: string;
}
type Magic = ((arg: PropsWithCb4) => 1) & ((arg: PropsWithPath4) => 2);
declare const magic: Magic;
// error
magic({
cb: () => {},
instantPopoup: true,
path: "df",
});
// 1, no error
magic({
cb: () => {},
instantPopoup: true,
})
// 2, no error
magic({
instantPopoup: true,
path: "df",
})
const trololo = {
cb: () => {},
instantPopoup: true,
path: "df",
}
magic(trololo); // 1, no error
null
(потому что именно такое значение по умолчанию ты передал).export const Context = createContext<{
sidebarIsOpen: boolean;
toggleSidebar: (value: boolean) => void;
} | null>(null)
или лучше export const Context = createContext({
sidebarIsOpen: false,
toggleSidebar: () => {}
});
if (instance instanceof Animal) { ... }
, как иначе то? Как-то ты же сейчас проверяешь какой метод вызвать specificAnimalMethod
или specificHumanMethod
? export type NavDataItem =
| {
type: 'a',
name: string;
link: string;
}
| {
type: 'b',
name: string;
children: NavDataItem[];
};
json
, лучше тыкнуть в консоли на ответе "Copy object" и вставь в любой конвертер, который гуглится по "json to ts", например https://app.quicktype.io/. Так ты точно не ошибёшься, а потом уже можешь уточнить тип руками. unknown
и прогонять через тайпгард, проверяя руками, что он соответствует типу, но это не частая практика, увы. export interface Post {
title: string;
content: Content[]; // мы ждём тут массив, а не кортеж из одного элемента
}
export type TContentType = "text" | "video" | "header" | "code" | "images" | "remark" | "materials";
// базовый интерфейс, чисто для надёжности, никуда не экспортируем
interface IContentBase {
type: TContentType
}
export interface ITextContent extends IContentBase {
type: "text";
value: string;
}
export interface IVideoContent extends IContentBase {
type: "video";
url: string;
}
// ...
export interface IOtherContent extends IContentBase {
type: "header" | "code" | "images" | "remark" | "materials";
}
// делаем union с type как discriminator field
export type Content = ITextContent | IVideoContent | IOtherContent;
const items: Post = {
title: "foo bar",
content: [
{type: "text", value: "lorem 1"},
{type: "video", url: "lorem 2"},
{type: "text", value: "lorem 3"}
// ...
]
};
// используем тайпгард, тайпскрипт недостаточно умный, чтоб вывести Extract<Content, { type: "text" }> в таких случаях
const onlyTextType: ITextContent[] = items.content.filter((it): it is ITextContent => it.type === "text");
// ...
<script>
php файл который сгенерирует простой скрипт устанавливавший заданные константы и в js, условно так: header("Content-Type: application/x-javascript");
define("CONSTANT", 1);
echo 'Object.assign(window,' . json_encode(
get_defined_constants(true)['user']
) . ');';