Skip to content

Instantly share code, notes, and snippets.

View michaeljscript's full-sized avatar
💻
Coding React Apps

Michal S michaeljscript

💻
Coding React Apps
View GitHub Profile
const data: unknown = response.body;
const maybePerson = parsePerson(data);
if (maybePerson) {
// maybePerson is Person
console.log('Welcome ' + maybePerson.name);
} else {
console.log('You are not a person!');
}
function checkType<T>(value: unknown, parse: (val: unknown) => T | null): value is T {
return parse(value) !== null;
}
const data: unknown = response.body;
if (checkType(data, parsePerson)) {
// data is Person
console.log('Welcome ' + data.name);
} else {
console.log('You are not a person!');
}
const createTypeGuard = <T>(parse: (val: unknown) => T | null) => (value: unknown): value is T => {
return parse(value) !== null;
}
const isPerson = createTypeGuard(parsePerson);
const data: unknown = response.body;
if (isPerson(data)) {
// data is Person
console.log('Welcome ' + data.name);
} else {
console.log('You are not a person!');
}
interface Person {
name: string;
age: number;
}
function isPerson(value: unknown): value is Person {
return typeof value === 'object' && value &&
value.hasOwnProperty('name') &&
value.hasOwnProperty('age') &&
typeof value.name === 'string' &&
typeof value.age === 'number';
}
interface Person {
name: string;
age: number;
something: string;
}
function parsePerson(value: unknown): Person | null {
if (
typeof value === "object" &&
value &&
value.hasOwnProperty("name") &&
value.hasOwnProperty("age") &&
value.hasOwnProperty("something")
) {
const { name, age, something } = value;
if (
declare global {
interface Object {
hasOwnProperty<K extends string>(key: K): this is Record<K, unknown>;
}
}