Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

typescript - is assignable to the constraint of type 'X', but 'X' could be instanciated with a different subtype of constraint ... when generic types are the same

// Utility type like Omit but does not loose the known keys
export type RemappedOmit<T, K extends PropertyKey> = {
  [P in keyof T as Exclude<P, K>]: T[P]
}
// Utility type that makes some keys optional
export type OptionalKeys<T, Keys extends keyof T> = RemappedOmit<T, Keys> &
  Pick<Partial<T>, Keys>


// Example of my problem
type ExtendedBase = Record<string, unknown>
type Props<Extended extends ExtendedBase> = {
  foo: string
  bar: string
} & Extended

const fn = <Extended extends ExtendedBase>(
  partialP: OptionalKeys<Props<Extended>, 'bar'>,
): Props<Extended> => {
  const r: Props<Extended> = { // 'RemappedOmit<Props<Extended>, "bar"> & { bar: string; }' is assignable to the constraint of type 'Extended', but 'Extended' could be instantiated with a different subtype of constraint 'Record<string, unknown>'.
    ...partialP,
    bar: 'smthg',
  }

  return r
}

Reproduction in TS Playground here

I think I understand that the type Prop<Extended> assigned to r could be instantiated with a different Extended type than the one from OptionalKeys<Props<Extended>, 'bar'>. In other circumstances I would totally understand. But it seems to me that in this context it could be statically analyzed that these both types are actually instantiated with the same Extended type coming from the generic function.

Am I right and is there any workaround this ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...