xiayy860612 / amos-tech-blog

http://tech.s2u2m.com/
0 stars 0 forks source link

TS 类型转换 #5

Open xiayy860612 opened 12 hours ago

xiayy860612 commented 12 hours ago
xiayy860612 commented 12 hours ago
const arrayWithFalsyValues: (string | null | undefined)[] = ['a', null, 'b', '', 'c', undefined, 'd'];

const filteredArray = arrayWithFalsyValues.filter(Boolean);

// filteredArray will be: ['a', 'b', 'c', 'd']
const isNotNullOrUndefined = <T>(value: T): value is NonNullable<T> => Boolean(value);

const filteredArray = arrayWithFalsyValues.filter(isNotNullOrUndefined);

// filteredArray will be: ['a', 'b', 'c', 'd']