Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Created May 10, 2022 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeDDHH/39c57381e3362fb113175627c1883a32 to your computer and use it in GitHub Desktop.
Save LeeDDHH/39c57381e3362fb113175627c1883a32 to your computer and use it in GitHub Desktop.
TypeScriptで型操作をする際の参考

undefinedが含まれた配列からundefinedを取り除く

// stringとundefinedが混合する配列
const items: (string | undefined)[] = ['a', undefined, 'b', undefined, 'c']

// Exclude<T,U>でT型にあるプロパティからU型に代入可能なプロパティを取り除いた型を構築する
// Exclude<typeof item, undefined>の場合、itemにあるundefinedを取り除いた型を定義する
const stringOrNumbers: string[] = items.filter(
    (item): item is Exclude<typeof item, undefined> => item !== undefined
)

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment