unknown | any
;(unknownValue as Function).call(null)
type UnpackArray<T> = T extends (infer R)[] ? R : T
type Foo = UnpackArray<typeof [{foo: 1}]> // { foo: number }
const foo: Record<string, number> = { bar: 1, tar: 2 }
export interface Foo;
export class Foo {
public bar() {
// code
};
}
export interface Bar extends Foo;
export class Bar {
public override bar() {
// override code
};
}
interface Props {
foo: number;
bar: string;
}
const obj: Partial<Props> = { foo: 1 }
console.assert
declare function assert(value: unknown, error: string | Error): asserts value;
asserts ... is ...
function assertIsObject(obj: unknown, errorMessage: string = 'Incorrect object!'): asserts obj is object {
if(typeof obj !== 'object' || obj === null) throw new Error(errorMessage)
}
function assertIsAddress(address: unknown): asserts address is User['address'] {
const errorMessage = 'Incorrect address!'
assertIsObject(address, errorMessage)
if(
!('city' in address) ||
!('state' in address) ||
!('country' in address) ||
!('postalCode' in address)
) throw new Error(errorMessage)
}
function assertIsUser(user: unknown): asserts user is User {
const errorMessage = 'Incorrect user!'
assertIsObject(user, errorMessage)
if(
!('id' in user) ||
!('username' in user) ||
!('email' in user)
) throw new Error(errorMessage)
assertIsAddress((user as User).address)
}
const foo = (value: number): number | never => {
if(value === 1) return value + 1
throw new Error('Not alone!')
}
function extend<T extends object, U extends object>(
value: T,
extension: U
): asserts value is T & U {
Object.assign(value, extension);
}
function indexById<T extends {}, D = Record<T['id'], Partial<T>>>(arr: T[]): D {
return arr.reduce((acc, { id, ...rest }) => ({ ...acc, [id]: rest }), {});
}
Example
``` interface User { name: string; id: string; } indexById([ { id: '001', name: 'Foo' }, { id: '002', name: 'Bar' }, ]); // { '001': { name: 'Foo'}, '002': { name: 'Bar' } } ```const obj = {
foo: 1,
bar: '',
}
type Prop = typeof keyof obj;
const animals = ['cat', 'dog', 'mouse'] as const
type Animal = typeof animals[number]
// const animals:Animal[] = ['cat', 'dog', 'mouse']
export const enum Say { bark = 'woof woof' } // WARN: with 'const' enum will not be exported as function
const say:Say = 'woof woof' as Say.bark;