Appearance
TypeScript Principles
The rules here are primarily based on the StyleGuide - TypeScript Deep Dive.
Interface
Interface should be named using PascalCase, without the I prefix. For example:
ts
interface ArticleAuthor {
// ...
}Type
For type declarations that are not semantically meaningful, do not add the "type" suffix.
Union
For union types, we recommend first defining them asenumtypes before converting them. Here's how to do it:
ts
enum HttpMethodType {
GET = 'get',
POST = 'post',
PUT = 'put',
DELETE = 'delete',
}
type HttpMethod = `${HttpMethodType}`;TIP
Since eslint doesn't check for duplicate strings (or numbers) in union types, but enum doesn't allow duplicate key values, it's easier to manage.
Enum
enumusesPascalCase, does not need the enum suffix, and if appropriate can include a type suffixenumtype members usePascalCase; member values useSCREAMING_SNAKE_CASE,camelCase,PascalCasestrings or numbers (depending on the usage context)
For example:
typescript
enum ArticleBlockType {
TEXT = 'TEXT',
IMG = 'IMG',
EMBED = 'EMBED',
AD = 'AD',
OTHER = 'OTHER',
}
enum PublicStatus {
PRIVATE,
PUBLIC,
}Class
- Class names use
PascalCase, and their members and methods usecamelCase(example:MyClass). - All class members and methods should specify access modifiers (
public,private,protected). Private members must be prefixed with an underscore, like_myPrivateMember.
For example:
typescript
class MyClass {
constructor(){
// do something...
}
public myPublicMember: string = 'hello';
private _myPrivateMember: string = 'secretToken';
protected myProtectedMember: string = 'protectedToken';
readonly myReadOnlyMember: number = 5566;
public myPublicMethod() {
// ...
}
private _myPrivateMethod() {
// ...
}
public get myGetterMethod() {
// ...
}
public static myStaticMethod() {
// ...
}
}Constant
Constants must be named in SCREAMING_SNAKE_CASE format, for example:
typescript
const FULL_DATA_TIME_FORMAT: string = 'YYYY-MM-DD HH:mm:ss';