美文网首页
TS TypeScript常用语法

TS TypeScript常用语法

作者: 初心不改_0055 | 来源:发表于2023-01-18 18:33 被阅读0次

vue组件props转为TS类型

import { ExtractPropTypes } from 'vue';
const props = {
  layout: {
    type: String as PropType<'inline' | 'grid' | 'vertical'>,
    default: 'inline',
  },
  labelWidth: {
    type: [Number, String] as PropType<number | 'auto'>,
    default: 'auto',
  },
  colon: {
    type: Boolean,
  },
  onChange: Function as PropType<(val: string) => void>,
};
// 语句
type Props = ExtractPropTypes<typeof props>;

效果

type Props = {
  layout: 'inline' | 'grid' | 'vertical';
  labelWidth: number | 'auto';
  colon: boolean;
  onChange?: ((val: string) => void) | undefined
};

取一个函数返回值的类型

function getVal() {
  return {
    name: 'jack',
    list: [
      {
        type: 'string',
        key: 'a',
      },
    ],
    status: true,
  };
}
// 语句
type Val = ReturnType<typeof getVal>

效果

type Val = {
  name: string;
  list: { type: string; key: string }[];
  status: boolean;
};

将TS类型的所有值转为可选值

type Val = {
  name: string;
  list: { type: string; key: string }[];
  status: boolean;
};
// 语句
type NewVal = Partial<Val>

效果

type NewVal = {
  name?: string | undefined;
  list?: { type: string; key: string }[] | undefined;
  status?: boolean | undefined;
};

将TS类型的所有值转为必选值

type Val = {
  name?: string | undefined;
  list?: { type: string; key: string }[] | undefined;
  status?: boolean | undefined;
};
// 语句
type NewVal = Required<Val>

效果

type NewVal = {
  name: string;
  list: { type: string; key: string }[];
  status: boolean;
};

相关文章

网友评论

      本文标题:TS TypeScript常用语法

      本文链接:https://www.haomeiwen.com/subject/wgxfhdtx.html