const で定義した定数を type として利用する
code:ts
/** 定数 */
export const ALPHABET_LIST_HEBREW = {
A: 'Aleph',
B: 'Bet',
G: 'Gimel',
// ...
} as const; // ここで as const と置くのがキモ
// const で定義した値を type として利用する
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions
type ALPHABET_HEBREW = typeof ALPHABET_LIST_HEBREWkeyof typeof ALPHABET_LIST_HEBREW; // 'A' | 'B' | 'G' | ...
/** 関数で利用 */
export const getAlphabetHebrew = (initial: ALPHABET_HEBREW) => {
// ここで initial の型は 'A' | 'B' | 'G' | ... となっている(タイプガード)
const col = alphabetsHebrew.find((alphabet: IAlphabet) => alphabet.initial === initial);
};
#TypeScript
Created by nishiyamayudai
👍 umamichi umamichi.icon がいいねしました on 2021/3/25