You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于对象数组的字段值定义TypeScript函数参数类型?

Great question! You absolutely can derive the allowed name values directly from your static array in TypeScript—here's how to do it cleanly:

Step 1: Lock down your array's type with as const

First, modify your array definition to use the as const assertion. This tells TypeScript to preserve the exact literal values of name and language instead of widening them to generic string types:

const arr = [
  {name: 'cat', language: 'meow'},
  {name: 'dog', language: 'bark'},
  {name: 'cow', language: 'moo'}
] as const;

Step 2: Define type X by extracting name values

Now you can create type X by pulling the union of all name literals from the array's type:

type X = typeof arr[number]['name'];
// This resolves to: type X = 'cat' | 'dog' | 'cow'

Step 3: Use X in your function

Apply this type to your function parameter, and TypeScript will enforce that callers only pass valid name values from the array:

function getLanguage(name: X) {
  const match = arr.find(item => item.name === name);
  // Since `name` is strictly limited to valid values, match will never be undefined
  return match!.language;
}

// Valid calls (TypeScript approves)
getLanguage('cat'); // Returns 'meow'
getLanguage('dog'); // Returns 'bark'

// Invalid call (TypeScript throws an error)
getLanguage('bird'); // Error: Argument of type '"bird"' is not assignable to parameter of type 'X'

Bonus: Get precise return types

If you want the function's return type to match the exact language string for each name (instead of a generic string), you can refine it further:

function getLanguage<T extends X>(name: T): (typeof arr[number] extends {name: T} ? typeof arr[number]['language'] : never) {
  const match = arr.find(item => item.name === name) as typeof arr[number] & {name: T};
  return match.language;
}

const catSound = getLanguage('cat'); // Type is 'meow' (not just string)
const cowSound = getLanguage('cow'); // Type is 'moo'

Key takeaway

The as const assertion is critical here—it prevents TypeScript from "widening" your literal values to broader types. Without it, arr would be typed as {name: string; language: string}[], and X would just be string, which defeats your goal of restricting input values.

内容的提问来源于stack exchange,提问作者Glstunna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:07:30