TypeScript Visual Studio Code Snippets

TypeScript Visual Studio Code Snippets

Fri Dec 30 2022343 words

Across projects and within web application you will find yourself creating a lot of repetitive boilerplate code. VS Code and other IDE's (integrated development environments) have support which allows you to include custom code snippets just by typing a reference to them. Using snippets allows you to rapidly scaffold a large application quickly and also speeds up day to day development. The following are TypeScript VS code snippets which can be used to quickly scaffold files.

To add a snippet in VS code go to - Code > Preferences > Configure User Snippets. You can create a snippet file for your local project, workspace, or globally.

A couple of important keys in the TypeScript VS code snippets:

  • scope - refers to the languages the snippet applies to
  • prefix - what you type to bring up the snippet

Placeholders such as ${1:name} etc can be used in code snippets with a default value and tabbed through in a sequence finishing on \t$0.


TypeScript constant VS Code snippet

  • ${1:type} - type name
  • ${2:name} - constant name
  • ${3:prop} - constant property name
  • ${4:1} - constant property value
  • \t$0 - ends on create new property
{
    "TypeScript constant": {
        "scope": "javascript,typescript,vue",
        "prefix": "ts-constant",
        "description": "TypeScript constant",
        "body": [
            "export const ${2:name} = <const>{",
            "    ${3:prop}: ${4:1},",
            "\t$0",
            "}",
            "",
            "export type ${1:type} = typeof ${2:name}[keyof typeof ${2:name}]"
        ],
    },
}

TypeScript interface VS Code snippet

  • ${1:name} - interface name
  • ${2:key} - interface property name
  • ${3:string} - interface property value
  • \t$0 - ends on create new property
{
    "TypeScript interface": {
        "scope": "javascript,typescript,vue",
        "prefix": "ts-interface",
        "description": "TypeScript interface",
        "body": [
            "export interface ${1:name} {",
            "    ${2:key}: ${3:string},",
            "\t$0",
            "}",
        ],
    }
}

Featured Articles