1. <template>
    2. <div class="about">
    3. <h1>This is an about page</h1>
    4. </div>
    5. </template>
    6. <script lang="ts">
    7. // ts 很好啊 开发人员要拥抱技术
    8. // 规定传递什么 就传递什么 目标比较明确
    9. // 规定它传入的属性 及属性的数据类型
    10. // 接口
    11. interface LabelValue {
    12. name: string;
    13. }
    14. // 可选属性
    15. interface SquareConfig {
    16. color?: string;
    17. width?: number;
    18. }
    19. // 只读属性
    20. interface Point {
    21. readonly x: number;
    22. readonly y: number;
    23. }
    24. // 函数类型
    25. interface SearchFunc {
    26. (source: string, substring: string): boolean;
    27. }
    28. // 接口也可以继承
    29. interface fa {
    30. name: string;
    31. }
    32. interface child extends fa {
    33. money: number;
    34. }
    35. // 混合类型
    36. import { defineComponent, onMounted } from "vue";
    37. export default defineComponent({
    38. setup() {
    39. let aa = (bb: LabelValue): void => {
    40. console.log("结果:", bb.name);
    41. };
    42. let create = (config: SquareConfig): { color: string; area: number } => {
    43. let newSquare = { color: "white", area: 1000 };
    44. if (config.color) {
    45. newSquare.color = config.color;
    46. }
    47. if (config.width) {
    48. newSquare.area = config.width * config.width;
    49. }
    50. return newSquare;
    51. };
    52. let p1: Point = { x: 10, y: 20 };
    53. // 只能读 不能改写
    54. // p1.x = 5;
    55. // 数组只读
    56. let arr: number[] = [3, 2, 5];
    57. let ro: ReadonlyArray<number> = arr;
    58. // 数组只读
    59. // ro[0] = 12; error
    60. // ro.push(5) error
    61. // ro.length = 100 error
    62. // arr = ro error
    63. // 可以采用类型断言覆写
    64. arr = ro as number[];
    65. arr[0] = 222;
    66. console.log("结果:", arr, ro);
    67. let mySearch: SearchFunc;
    68. mySearch = (source, substring) => {
    69. let result = source.search(substring);
    70. return result > -1;
    71. };
    72. console.log("结果:333", mySearch("xiaohua", "p"));
    73. let kk = <child>{};
    74. kk.name = "kk";
    75. kk.money = 20;
    76. console.log("结果:kk", kk);
    77. onMounted(() => {
    78. let obj = {
    79. name: "xiaoming",
    80. };
    81. aa(obj);
    82. console.log("结果:", create({ color: "black", width: 5 }));
    83. });
    84. },
    85. });
    86. </script>