<!-- DogImagesContainer.vue -->
<template>
<DogImages :dogs="dogs" />
</template>
<script setup>
import { ref, onMounted } from "vue";
import DogImages from "./DogImages.vue";
const dogs = ref([]);
onMounted(async () => {
const response = await fetch(
"https://dog.ceo/api/breed/labrador/images/random/6"
);
const { message } = await response.json();
dogs.value = message;
});
</script>
<template>
<slot :checkbox="checkbox" :toggleCheckbox="toggleCheckbox"></slot>
</template>
<script setup>
import { ref, reactive } from "vue";
const API_ENDPOINT_URL = "https://official-joke-api.appspot.com/random_joke";
const data = reactive({
setup: null,
punchline: null,
});
const loading = ref(false);
const fetchJoke = async () => {
loading.value = true;
const response = await fetch(API_ENDPOINT_URL);
const responseData = await response.json();
data.setup = responseData.setup;
data.punchline = responseData.punchline;
loading.value = false;
};
fetchJoke();
</script>
// usage
<template>
<DataProvider v-slot="{ data, loading }">
<div class="joke-section">
<p v-if="loading">Joke is loading...</p>
<p v-if="!loading">{{ data.setup }}</p>
<p v-if="!loading">{{ data.punchline }}</p>
</div>
</DataProvider>
<DataProvider v-slot="{ data, loading }">
<p v-if="loading">Hold on one sec...</p>
<div v-else class="joke-section">
<details>
<summary>{{ data.setup }}</summary>
<p>{{ data.punchline }}</p>
</details>
</div>
</DataProvider>
</template>
<script setup>
import DataProvider from "./components/DataProvider.vue";
</script>
<!-- MouseTracker.vue -->
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const x = ref(0)
const y = ref(0)
const update = e => {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>
<template>
<slot :x="x" :y="y"/>
</template>
type Pozdrav = `ahoj${string}`;
let ok: Pozdrav = "ahojsvete"; // ✅
let nok: Pozdrav = "nazdar"; // ❌ musí začínat "ahoj"
// -------------------- //
type Velikost = "small" | "medium" | "large";
type Barva = "red" | "blue";
type TrickoSVelikosti = `${Velikost}-${Barva}`;
let tricko: TrickoSVelikosti = "small-red"; // ✅
let tricko2: TrickoSVelikosti = "small-green"; // ❌ green není v typu Barva
// -------------------- //
// Uppercase/Lowercase - převod na velká/malá písmena
type Pozdrav = "ahoj" | "nazdar";
type KriciciPozdrav = `${Uppercase<Pozdrav>}!`; // typ je "AHOJ!" | "NAZDAR!"
// Capitalize - první písmeno velké
type Capitalize<S extends string> = `${Uppercase<S[0]>}${Lowercase<S>}`;
type Jmeno = Capitalize<"petr">; // typ je "Petr"
// -------------------- //
// string s přesnou délkou 2
type DvaPismena = string & { length: 2 };
type Status = `${DvaPismena}-${number}`;
let ok: Status = "OK-123"; // ✅
let nok: Status = "OK1-123"; // ❌ první část musí mít délku 2
// -------------------- //
type Email = `${string}@${string}.${string}`;
let email: Email = "test@example.com"; // ✅
let neplatny: Email = "testexample.com"; // ❌ chybí @
// -------------------- //
// Definujeme povolené hex znaky
type HexDigit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
| "a" | "b" | "c" | "d" | "e" | "f";
// Přesná definice hex barvy
type HexColor = `#${HexDigit}${HexDigit}${HexDigit}${HexDigit}${HexDigit}${HexDigit}`;
let barva1: HexColor = "#ff00ff"; // ✅
let barva2: HexColor = "#ff00"; // ❌ příliš krátké
let barva3: HexColor = "#gg0000"; // ❌ 'g' není hex digit
// 1. Primitivní typy - lze zjednodušit
// S generics:
function processValue<T extends string>(value: T) { }
// Jednodušeji:
function processValue(value: string) { }
// 2. Union typy - lze zjednodušit
type Fruit = "apple" | "banana" | "orange";
// S generics:
function processFruit<T extends Fruit>(fruit: T) { }
// Jednodušeji:
function processFruit(fruit: Fruit) { }
// 3. Literal typy - lze zjednodušit
// S generics:
function processLiteral<T extends "yes" | "no">(answer: T) { }
// Jednodušeji:
function processLiteral(answer: "yes" | "no") { }
// 4. Array typy - lze zjednodušit v základním případě
// S generics:
function processArray<T extends any[]>(arr: T) { }
function processStringArray<T extends string[]>(arr: T) { }
// Jednodušeji:
function processArray(arr: any[]) { }
function processStringArray(arr: string[]) { }
// 5. Function typy - lze zjednodušit
type Logger = (msg: string) => void;
// S generics:
function withLogging<T extends Logger>(logger: T) { }
// Jednodušeji:
function withLogging(logger: Logger) { }
// 6. Class typy - lze zjednodušit v základním případě
class Animal { }
// S generics:
function processClass<T extends Animal>(instance: T) { }
// Jednodušeji:
function processClass(instance: Animal) { }
// 7. Generický typ s extends - POUZE PŘES GENERIC CONSTRAINT
interface Box<T> {
value: T;
}
interface NumberBox<T extends number> extends Box<T> {
increment(): void;
}
// 8. Kombinace více typů - lze zjednodušit
type StringWithLength = string & { length: number };
// S generics:
function processString<T extends string & { length: number }>(value: T) { }
// Jednodušeji:
function processString(value: StringWithLength) { }
// 9. Conditional type - POUZE PŘES GENERIC CONSTRAINT
type NonNullable<T> = T extends null | undefined ? never : T;
/*
omezení, která můžeme přidat na generické typy, aby splňovaly určité podmínky.
*/
// T musí být objekt
function getProperty<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Použití:
const person = { name: "Jan", age: 30 };
const name = getProperty(person, "name"); // OK
const invalid = getProperty(person, "invalid"); // Chyba - 'invalid' není klíč v person
// Casting = přetypování v TS nelze
// Asserce je explicitni určený typu
/*
: = type annotation (deklarace typu)
as / <> = type assertion (casting)
<T> = generic type parameter (generika)
*/
// Oba tyto řádky dělají totéž - type assertion/casting
let value: any = "hello";
let length1 = (value as string).length; // "as" syntax
let length2 = (<string>value).length; // "angle bracket" syntax
/ 1. Type annotation
let myStr: string = "hello";
// 2. Type assertion (as) - když TS neví typ
let someValue: any = "hello";
let strLength = (someValue as string).length;
// 3. Type assertion (angle brackets) - stejné jako 2
let strLength2 = (<string>someValue).length;
// 4. Generic type parameter
let myObs: Observable<number>;
let x: unknown;
x = [];
// 1
let result = (x as number[]).push(111);
// 2
let result = (<number[]>x).push(111);
| Utility Typ | Použití na | Akce (Whitelist/Blacklist) | Popis | Podobné Funkce |
|---|---|---|---|---|
Pick |
Objekty | Whitelist | Vybere určité klíče z objektu a vytvoří nový typ. | Extract |
Omit |
Objekty | Blacklist | Odstraní specifikované klíče z objektu a vytvoří nový typ. | Exclude |
Partial |
Objekty | - | Změní všechny vlastnosti objektu na volitelné. | - |
Required |
Objekty | - | Změní všechny vlastnosti objektu na povinné. | - |
Readonly |
Objekty | - | Změní všechny vlastnosti objektu na pouze pro čtení. | - |
Record |
Typy | - | Vytvoří typ objektu s konkrétními klíči a hodnotami daného typu. | - |
Exclude |
Typy | Blacklist | Odstraní určité hodnoty z union typu. | Omit |
Extract |
Typy | Whitelist | Vybere pouze specifikované hodnoty z union typu. | Pick |
NonNullable |
Typy | Blacklist | Odstraní null a undefined z typu. |
- |
// union
type StringOrNumber = string | number;
// intersection
type User = { id: number };
type Admin = { isAdmin: boolean };
type AdminUser = User & Admin; // { id: number; isAdmin: boolean; }
// return type
type GetUserType = () => { id: number; name: string };
type UserType = ReturnType<GetUserType>; // { id: number; name: string }
// return type pres interface
interface StringFormat {
(str: string, isUpper: boolean): string;
}
let format: StringFormat;
format = function (str: string, isUpper: boolean) {
return isUpper ? str.toLocaleUpperCase() : str.toLocaleLowerCase();
};
console.log(format('hi', true));
/*
NonNullable je utility typ v TypeScriptu, který odstraní null a undefined z daného typu. To znamená, že výsledný typ bude obsahovat všechny hodnoty z původního typu kromě null a undefined
NonNullable<T>
*/
// 1
type UserInput = string | number | null | undefined;
function processUserInput(input: NonNullable<UserInput>) {
console.log(`Processing user input: ${input}`);
}
processUserInput('Hello');
processUserInput(42);
// Below would cause compile-time errors:
processUserInput(null);
processUserInput(undefined);