【问题标题】:Is it possible to filter out keys from an interface / type?是否可以从接口/类型中过滤掉键?
【发布时间】:2021-12-22 19:20:23
【问题描述】:

比如我有一个接口:

interface Foo {
  name: string;
  id: number;
}

我只想要string 类型的键。我设法将id 的类型更改为never,并从Foo 获取所有密钥。但是id 仍然是一个有效的密钥,只是类型为never

const bar: keyof Partial<{ [K in keyof Foo ]: Foo [K] extends string ? Foo [K] : never }> = 'id';

我如何从Foo 获取类型为string 的密钥?

我想要的是:

const bar: FooStringKeys = 'name'; // ok
const bar: FooStringKeys = 'id;    // error

【问题讨论】:

标签: typescript types interface key


【解决方案1】:

取自mapped types docs。 TS Playground 版here.

interface Foo {
  name: string;
  id: number;
}

// Generic string property extractor
type StringsOnly<Type> = {
    [Property in keyof Type as Extract<Property, Type [Property] extends string ? Type [Property] : never>]: Type[Property]
};

// Foo *string* Properties
type FooString = StringsOnly<Foo>

const fooString: FooString = {name: 'hello'}
const notFooString: FooString = {id: 2} // error

// Foo *string* Key names
type FooStringKey = keyof FooString

const fooStringKey: FooStringKey = "name"
const notFooStringKey: FooStringKey = "id" // error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2011-03-11
    相关资源
    最近更新 更多