type StepFn = (val?: number) => number | StepFn;
function add(val: number): typeof add;
function add(val: 0): number;
function add(): number;
function add(val?: number): number | StepFn {
if (val) {
return function sum(next?: number): number | StepFn {
if (!next) {
return val;
}
return add(val + next);
};
} else {
return 0;
}
}
console.log(add());
console.log(add(1)(2)());
console.log(add(2)(4)(6)());
console.log(add(4)(6)(8)(10)());
class C {
getName() {
return 'Jack'
}
}
class B extends C {
}
class A extends B {
getName(params?: { countryCode: string }) {
return params?.countryCode === 'ru' ? 'Джек' : super.getName()
}
}
RegExp
. Любой класс который его расширяет туда подойдётinterface ChtotoTam {
f: RegExp
}
function foo<K extends keyof State>(key: K, callback: (value: State[K]) => void) {
// ...
}
function f<X extends { [index: string]: string }>(someObj: X, someEnum: keyof X): string {
return someObj[someEnum];
}
"typescript.suggest.completeFunctionCalls": true,
"javascript.suggest.completeFunctionCalls": true,
class UserModel {
email: string;
password: string;
}
class UserDTO {
protected __guard: never; // добавляем фиктивное поле
email: string;
}
const getUser = async (email: string): Promise<UserDTO> => {
const user = await db.find(email);
return user; // Ошибка, как заказывали
}
interface PostAttachVideo {
type: 'video'
attach: AttachVideo
}
interface PostAttachAudio {
type: 'audio'
attach: AttachAudio
}
type PostAttach = PostAttachAudio | PostAttachVideo
function isAudio(attach: PostAttach): attach is PostAttachAudio {
return attach.type === 'audio';
}
const [a, b, c, d, f, g= ''] = value.match(/\d+/g)!;
const [a, b, c, d, f, g= ''] = value.match(/\d+/g) || [];
interface ModelOptionRange {
value: [ number, number ];
range: true;
}
interface ModelOptionValue {
value: number;
range: false;
}
type ModelOption = ModelOptionRange | ModelOptionValue;
function check(v: number, cond: ModelOption): boolean {
if (cond.range) {
// тут cond точно типа ModelOptionRange
const [ min, max ] = cond.value;
return (min <= v && v <= max);
} else {
// а тут ModelOptionValue
return v === cond.value;
}
}
// Эта функция определена где-то в другом месте (для примера вместо AsyncStorage)
declare function someMagic(key: string): string | null;
type StoreTypes = {
theme: 'light' | 'dark' | null;
auth: 'true' | 'false' | null;
}
// Собственно декларация функции
function getKey<K extends keyof StoreTypes>(key: K): StoreTypes[K] {
return someMagic(key) as StoreTypes[K];
}
// type t = "light" | "dark" | null
const t = getKey('theme');
// type a = "true" | "false" | null
const a = getKey('auth');
// ошибка "test" не является ключом в StoreTypes
const x = getKey('test');