加强索引中键的边界

时间:2019-05-23 10:44:27

标签: typescript generics keyof

我正在尝试使用将索引作为参数的函数,其中键限制为T键

import os
import glob
from pathlib import Path

cwd = os.getcwd()

directory = cwd

output = cwd

txt_files = os.path.join(directory, '*.txt')

for txt_file in glob.glob(txt_files):
    cpath =(Path(txt_file).resolve().stem)

    nametxt = "-".join(cpath.split('_')[0:1])
    amendtext = "|  " + nametxt

    src=open(txt_file, errors='ignore')

    lines = src.read().splitlines()
    src.close

    src = open(txt_file, "w")
    src.write('\n'.join([amendtext +line for line in lines]))

有没有实现这一目标的方法?这是正确的方法吗?

1 个答案:

答案 0 :(得分:2)

索引签名参数只能是numberstring(甚至不能是number | string

您正在寻找映射类型,特别是Record映射类型:

function aliasSet<T>(values: Record<keyof T, string>)

例如:

declare function aliasSet<T>(values: Record<keyof T, string>) : void;
interface O {
    foo: number,
    bar?: boolean
}

aliasSet<O>({
    bar: "", // Record erases optionality, if you want all to be optional you can use Partial<Record<keyof T, string>>
    foo: ""
})