Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

TypeScript: How to map objects in a discriminated union to functions they can be called with?

In vanilla JS, I'm able to write some code that looks something like the following:

function renderTextField(props) { }
function renderSelectField(props) { }

const fieldMapping = {
    text: renderTextField,
    select: renderSelectField,
};

function renderField(field) {
    const renderFn = fieldMapping[field.type];
    renderFn(field.data);
}

Using 2 types of fields just to keep the example small, but the nice thing about this code is that the generic method doesn't need to know about the type of field, and it delegates the decision to the mapping provided by fieldMapping.

I'm trying to write something similar in TypeScript. But I can't figure out how to get the types to work and still use an object to provide a mapping between type and the function to delegate to.

I realise that I could use a switch statement or conditionals instead of an object to map things, but I would prefer to do it this way if at all possible.

type TextFieldData = { value: string }
type TextField = { type: 'text', data: TextFieldData }
type SelectFieldData = { options: string[], selectedValue: string }
type SelectField = { type: 'select', data: SelectFieldData }
type FormField = TextField | SelectField

function renderTextField(props: TextFieldData) {}
function renderSelectField(props: SelectFieldData) {}

const fieldMapping = {
  text: renderTextField,
  select: renderSelectField,
}

// This won't work!
function renderFieldDoesNotWork(field: FormField) {
  const renderFn = fieldMapping[field.type]

  // Type 'TextFieldData' is missing the following properties from type 'SelectFieldData': options, selectedValue
  renderFn(field.data)
}

// This works
function renderFieldWorks(field: FormField) {
  if (field.type === 'text') {
    const renderFn = fieldMapping[field.type]
    renderFn(field.data)
  } else if (field.type === 'select') {
    const renderFn = fieldMapping[field.type]
    renderFn(field.data)
  }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I'm afraid that you're going to have to use a type assertion to avoid code duplication here. TypeScript's type system just doesn't have good support for these "correlated record types" or any manipulation that relies on the interaction of two union-typed values where the unions are not independent.

You've already arrived at the redundant-code-in-switch-statement workaround; here's the unsafe-assertion workaround:

function assertNarrowFunction<F extends (arg: any) => any>(f: F) {
  return f as (arg: Parameters<F>[0]) => ReturnType<F>; // assert
}

That takes a function of a union type like ((a: string)=>number) | ((a: number)=>boolean) and unsafely narrows it to a function which takes the union of its parameter types and returns the union of its return type, like ((a: string | number) => string | number). This is unsafe because a function of the former union type could be something like const f = Math.random()<0.5 ? ((a: string)=>a.length) : ((a: number)=>number.toFixed()), which definitely does not match ((a: string | number) => string | number). I can't safely call f(5) because maybe f is the string-length function.

Anyway, you can use this unsafe narrowing on renderFn to silence the error:

function renderFnAssertion(field: FormField) {
  const renderFn = assertNarrowFunction(fieldMapping[field.type]);
  renderFn(field.data); // okay
}

You've lied to the compiler a bit about the type of renderFn... not so much that it will accept any old argument (e.g., renderFn(123) will fail as desired), but enough that it would allow this:

function badRenderFn(field1: FormField, field2: FormField) {
  const renderFn1 = assertNarrowFunction(fieldMapping[field1.type]);
  renderFn1(field2.data); // no error!!! ooops
}

So you have to be careful.

Okay, hope that helps; good luck!

Link to code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...