Typescript 扩展或重写类型字段

Typescript 扩展或重写类型字段,typescript,generics,Typescript,Generics,我需要一个类型声明,允许值字段具有类型字符串,并且所有其他字段保持不变。我认为它很简单,而且写得很好 type WithValue<T> = T & { value: string; } 我希望最后一行是错误的,因为分配了编号,而不是字符串 我也尝试过一个领域,但这导致: type Diff=({[P in T]:P}&{[P in U]:never}&{[x:string]:never}[T]; 类型省略=拾取; 声明var z:WithValue; z、 value=

我需要一个类型声明,允许
字段具有类型
字符串
,并且所有其他字段保持不变。我认为它很简单,而且写得很好

type WithValue<T> = T & { value: string; }
我希望最后一行是错误的,因为分配了
编号
,而不是
字符串


我也尝试过一个领域,但这导致:

type Diff=({[P in T]:P}&{[P in U]:never}&{[x:string]:never}[T];
类型省略=拾取;
声明var z:WithValue;
z、 value=“”;
z、 值=1;//错误-正确
z、 aghj=0;//错误-我不想要这个错误

如何以稍微不同的方式定义您的类型:

type WithValue<T> = { [K in keyof T]: T[K] } & { value: string };
type WithValue={[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...
声明常量x:WithValue;
声明常量:WithValue
x、 value.charAt(0);//好的,因为x.value的类型是string。
x、 asdf.whatever;//好的,因为x.asdf有any类型。
x、 值=1;//错误:类型编号不可分配给类型字符串。
y、 value.charAt(0)//好的,因为y.value有string类型;
y、 a//推断为具有类型编号|未定义(因为它是可选的)
y、 asdf.whatever//错误:类型上不存在asdf。。。

@Behrooz,除
外的任何字段将成为
任何
,但
将成为
字符串
。我还想在编辑器的自动完成列表中查看
value
y是任意。您使用的是什么版本的Typescript?@banan3'14,出现了什么错误?我不希望你引用的行有任何错误。``var y=f(x);//y是任意^ReferenceError:x未在对象上定义。(…/with.ts:9:11)``Versions:``ts node v5.0.1 node v8.10.0 typescript v2.7.2````banan3'14,这是因为您运行的代码对不存在的var使用
声明var
。我需要编译时错误在
y.value=1。太好了!甚至看起来很简单:)
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...