gpt4 book ai didi

typescript - 扩展或覆盖类型字段

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:34 26 4
gpt4 key购买 nike

我需要一个授予 value 的类型声明类型为 string 的字段所有其他字段都没有改变。觉得很简单就写了

type WithValue<T> = T & { value: string; }

不幸的是,在某些情况下我需要 T成为any .这会导致问题 - WithValue<any>变成一个any . 如何覆盖 any 的属性类型?


考虑关注 code :

type WithValue<T> = T & { value: string; }

function f<T extends object>(x: T): WithValue<T> {
return {...x as any, value: ""};
}

declare var x: any;

var y = f(x); // y is any
y.value = 1; // no error

我希望最后一行是错误的,因为分配了 number而不是 string .


我也试过 to omit一个领域,但这导致了another problem :

type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;

declare var z: WithValue<Omit<any, 'value'>>;
z.value = "";
z.value = 1; // Error - Correct
z.aghj = 0; // Error - I don't want this error

最佳答案

定义你的类型有点不同:

type WithValue<T> = { [K in keyof T]: T[K] } & { value: string };

然后,使用它,它似乎符合您的标准:

declare const x: WithValue<any>;
declare const y: WithValue<{a?: number}>

x.value.charAt(0); // Okay, since x.value has type string.
x.asdf.whatever; // Okay, since x.asdf has type any.

x.value = 1; // Error: Type number not assignable to type string.

y.value.charAt(0) // Okay, since y.value has type string;
y.a // Inferred to have type number | undefined (since it's optional)

y.asdf.whatever // Error: asdf does not exist on type...

关于typescript - 扩展或覆盖类型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com