TypeScript
We use TypeScript to statically type-check and build our frontend.
So do not install anything rather than
nuxt
and @nuxt/typescript
. And it just works.@nuxt/axios
that adds$axios
property tovue
andvuex
$style
property onVue
components to supportcss-modules
- global
.vue
files support fortypescript
Sometimes you want to make some runtime type checks: inside API methods, input validations, etc.
And since TypeScript types are only allowed during static check, we cannot use them in runtime.
That's how building runtime types is done:
import * as ts from 'io-ts'
// Runtime type, that can be used for schema validation:
export const RawComment = ts.type({
'id': ts.number,
'body': ts.string,
'email': ts.string,
})
// Static TypeScript type, that can be used as a regular `type`:
export type RawCommentType = ts.TypeOf<typeof RawComment>
And then validating it:
import * as ts from 'io-ts'
import * as tPromise from 'io-ts-promise'
async function fetchComments ($axios): Promise<RawCommentType[]> {
const response = await $axios.get('comments')
// Now we are sure that `response.data` has the correct runtime type:
return tPromise.decode(ts.array(RawComment), response.data)
}
That's a powerful combination of runtime and static type checking that enforces strong contracts on data exchange and keeping it up-to-date.
Last modified 1yr ago