ts,如何修改接口中某个字段的类型呢?

比如

interface A {
    type: string;
    age: number;
    list: {
        id:number;
        name: string;
        sex: number;
    }[]
}

我想要把 sex 修改为类型 string ,要怎么修改呢?

阅读 7.3k
4 个回答

upd:

type ValueOf<T> = T[keyof T]

interface B extends Omit<A, 'list'> {
    list: Omit<ValueOf<A['list']>, 'sex'> & {
        sex: string
    }[]
}

interface B extends Omit<A, 'age'> {
  age: string
}

覆盖的话,就比较麻烦了

问题不太清晰,猜测你是想 “类型断言”,可以直接使用 as 语法或者 <> 语法。
比如使用时:

interface A {
  type: string;
  age: number;
}

const age = '1';
const o: A = { type: 's', age: age as unknown as number };

参考官方文档:https://www.typescriptlang.or...

如果不是上述,直接再声明一个类型别名覆盖 age 类型即可:

interface A {
  type: string;
  age: number;
}
type B = Omit<A, 'age'> & { age: string };
interface A {
    type: string;
    age: number;
    list: {
        id: number;
        name: string;
        sex: number;
    }[]
}

const aas: Omit<A, 'list'> & { list: Array<{ id: number, name: string, sex: string }> } = {
    type: 'asd',
    age: 1,
    list: [{
        id: 11,
        name: 'sad',
        sex: 'sadsa'
    }]
};
新手上路,请多包涵
type InferArray<T> = T extends (infer U)[] ? U : never;

interface AA extends Omit<A, 'list'> {
  list: (Omit< InferArray< A['list']>, 'sex'>)[] & {
    sex: string
  }[]
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题