[TS] Snippets
ENUM
假設我們的 enum 是這樣:
enum GENDER {
MALE = 'male',
FEMALE = 'female',
}
把 enum 的 values 變成 union type(values of enum to type )
Typescript: string literal union type from enum @ StackOverflow
在 Template Literal Types 出來之後,要把 enum 的 values 變成 union type 非常簡單:
// get type from values of enum
type valueAsUnion = `${GENDER}`; // "male" | "female"
把 enum 的 keys 變成 union type (keys of enum to type)
// get type from keys of enum
type keyAsUnion = keyof typeof GENDER; // "MALE" | "FEMALE"
之所以可以這樣使用,是因為 typeof GENDER
會是該 enum 的物件形式:
const gender: typeof GENDER = {
MALE: GENDER.MALE,
FEMALE: GENDER.FEMALE,
};
把 enum 的 values 變成 object key(values of enum to object key)
keywords: enum value as key
可以使用 Record
:
enum GENDER {
MALE = 'male',
FEMALE = 'female',
}
type Gender = Record<GENDER, string>;
// type Gender = {
// male: string;
// female: string;
// }
也可以使用 Mapped Type:
enum GENDER {
MALE = 'male',
FEMALE = 'female',
}
type Gender = { [P in GENDER]: string };
// type Gender = {
// male: string;
// female: string;
// }
不使用 ENUM
延伸閱讀
Why it is not good to use enums? @ StackOverflow
使用 Array 搭配 literal String
const brands = ['Apple', 'Samsung', 'Sony', 'Xiaomi'] as const;
type Brand = typeof brands[number];
使用 const object
const BRAND = Object.freeze({
APPLE: 'Apple',
SAMSUNG: 'Samsung',
XIAOMI: 'Xiaomi',
SONY: 'Sony',
} as const);
type Brand = typeof BRAND[keyof typeof BRAND];
錯誤 處理
- 把
err
定義成unknown
- 搭配
err instanceof Error
這個 type guard
function foobar() {}
try {
foobar();
} catch (err: unknown) {
if (err instanceof Error) {
console.log(err.stack);
} else {
console.log(err);
}
}
解構賦值後搭配 as
const allPostsData = fileNames.map((fileName) => {
// ...
return {
id,
...(matterResult.data as { date: string; title: string }),
};
});
JSON type
type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| {
[k: string]: JSONValue;
};
const result: JSONValue = {
name: 'Aaron',
languages: ['zh-TW', 'en-US'],
};