Function Type Expressions
The simplest way to describe a function is with a function type expression.
These types are syntactically similar to arrow functions:
function (: (: string) => void) {
('Hello World')
}
function (: string) {
.()
}
()
The simplest way to describe a function is with a function type expression.
These types are syntactically similar to arrow functions:
function (: (: string) => void) {
('Hello World')
}
function (: string) {
.()
}
()
Imagine we have a function called padLeft.
function (: number | string, : string): string {
throw new ('Not implemented yet!')
}
string, number, and booleanJavaScript has three very commonly used primitives: string, number, and boolean.
number: JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number
<script setup>当使用 <script setup> 时,defineProps() 宏函数支持从它的参数中推导类型:
<script setup lang="ts">
const props = defineProps({
foo: {
type: String,
required: true,
},
bar: Number,
})
props.foo // string
props.bar // number | undefined
</script>
Vue 本身就是用 TypeScript 编写的,所有的 Vue 官方库都自带了类型声明文件,开箱即用。
通过 create-vue 搭建的项目包含了预先配置好的 tsconfig.json。其底层配置抽象于 @vue/tsconfig 包中。
手动配置 tsconfig.json 时,请留意以下选项:
compilerOptions.isolatedModules 应当设置为 true,因为 Vite 使用 esbuild 来转译 TypeScript,并受限于单文件转译的限制。
如果你正在使用选项式 API,需要将 compilerOptions.strict 设置为 true (或者至少开启 compilerOptions.noImplicitThis,它是 strict 模式的一部分),才可以获得对组件选项中 this 的类型检查。否则 this 会被认为是 any。
如果你在构建工具中配置了路径解析别名,例如 @/\* 这个别名被默认配置在了 create-vue 项目中,你需要通过 compilerOptions.paths 选项为 TypeScript 再配置一遍。
我们可以使用 reactive() 函数创建一个响应式对象或数组:
<script setup>在 setup() 函数中手动暴露大量的状态和方法非常繁琐。幸运的是,我们可以通过使用构建工具来简化该操作。
当使用单文件组件(SFC)时,我们可以使用 <script setup> 来大幅度地简化代码。
当你更改响应式状态后,DOM 会自动更新。然而,你得注意 DOM 的更新并不是同步的。
相反,Vue 将缓冲它们直到更新周期的 “下个时机” 以确保无论你进行了多少次状态更改,每个组件都只更新一次。
下面的代码是用来按数组对象的指定属性来排序。
export const groupBy = (arr: any[], key: string): any[] | null => {
if (arr) {
const grouped = arr.reduce((group: any, obj: any) => {
const data = obj[key]
group[data] = group[data] ?? []
group[data].push(obj)
return group
}, {})
return grouped
}
return null
}